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

xu3bshqb  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(137)

在本例中,我使用puppeteer chrome headless browser和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.jstwitter.jsdatabase,jsutilities.js等。问题是我需要在几乎每个文件中声明这4个变量,在每个函数中传递它们似乎很愚蠢。我也不能在每个文件中重新声明它们,因为这会打开一个新的chrome浏览器并建立一个新的数据库连接。

9q78igpj

9q78igpj1#

假设你有一个文件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); 
}

相关问题