当使用所有文件都需要的模块时,如何在多个文件中拆分代码?

How to split code in multiple files when using a module like that is required for all files?

在这种情况下,我使用的是 puppeteer chrome 无头浏览器和 mongoDb。这是我的代码:

var browser = await puppeteer.launch()
var page = await browser.newPage()
var db = await MongoClient.connect("mongodb://localhost:27017/bot")
var scraped_users = db.collection("scraped_users")

我想将我的代码拆分成相关文件,如 "chrome.js"、"twitter.js"、"database,js"、"utilities.js"。问题是我几乎在每个文件中都需要上面声明的那 4 个变量,在每个函数中传递它们似乎很愚蠢。我也不能在每个文件中重新声明它们,因为那样会打开一个新的 chrome 浏览器并建立一个新的数据库连接。

假设您可以拥有文件 init.js:

/*let isInitialized, browser, page, db, scraped_users

async function init() {
  if (!isInitialized) {
    browser = await puppeteer.launch()
    page = await browser.newPage()
    db = await MongoClient.connect("mongodb://localhost:27017/bot")
    scraped_users = db.collection("scraped_users")
    isInitialized = true
  }
  return { browser, page, db, scraped_users }
}

module.exports = init*/

let common = {}; //store some global's.

//this should only be called once, eg. when App starts
common.init = async function () {      
  this.browser = await puppeteer.launch()
  this.page = await this.browser.newPage()
  this.db = await MongoClient.connect("mongodb://localhost:27017/bot")
  this.scraped_users = this.db.collection("scraped_users")      
}

module.exports = common;

然后像这样使用它:

/*const init = require('./init.js')

init().then(({browser, page, db, scraped_users}) => {
  console.log(browser, page, db, scraped_users)
})*/

const common = require('./common');
const doSomething = require('./do-something');

async function run() {
  await common.init(); //this only needs to be done once
  console.log(common.browser); //etc
  await doSomething();
}

//now inside other units, eg. do-something.js
const common = require('./common');
async function doSomething() {
  console.log(common.browser); 
}