假设您可以拥有文件 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);
}