如何在Node.js中的多个文件中分割代码?
问题描述:
我想分割我的代码在多个文件,但它不工作,我不知道为什么。如何在Node.js中的多个文件中分割代码?
我有3个文件,main.js,common.js和doSomething.js。 common.browser
是一个chrome实例,所以重要的是它只启动一次,并且我可以从每个文件访问它。
在我的代码下面,它不工作。 common.browser
在doSomething.print()
//File 1: main.js
(async() => {
const common = require('./common')
const doSomething = require('./doSomething')
await common.init()
doSomething.print() //<-- prints 'undefined'
})()
//File 2: common.js
const puppeteer = require('puppeteer')
let common = {}
common.init = async() => {
common.browser = await puppeteer.launch()
}
module.exports = common
//File3: doSomething.js
const common = require('./common')
let doSomething = {}
const browser = common.browser //<-- Added this and it makes it not work.
doSomething.print =() => {
console.log(browser)
}
module.exports = doSomething
答
未定义在你common.js
文件你在这里设置this.browser = await puppeteer.launch()
,关键字this
没有指向对象common
。
您可以简单地使用通用对象。
//File 2: common.js
const puppeteer = require('puppeteer')
let common = {}
common.init = async() => {
common.browser = await puppeteer.launch()
}
module.exports = common
或者,如果你想使用this
,你必须给共同构造并创建实例。
const puppeteer = require('puppeteer')
const common = function() {}
common.prototype.init = async function() {
this.browser = await puppeteer.launch()
};
module.exports = new common()
和以前一样与类语法(你需要节点8.xx)
const puppeteer = require('puppeteer')
class Common {
constructor() {}
async init() {
this.browser = await puppeteer.launch();
}
}
module.exports = new Common();
尝试增加.js文件的每个文件,至少这是我做的方式,也尽量require_once – SPlatten
'''''''''''''''''''const const puppeteer = require('puppeteer')' - 尝试在这里输入'。/ puppeteer',您缺少'。/' –
'doSomething.print()//