我试图将我的代码拆分为多个文件,但它无法正常工作,我不确定原因。
我有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
答案 0 :(得分:1)
在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();
答案 1 :(得分:1)
我正在测试解决方案,但出现错误。我可以在文件3中添加“异步”来使其工作。我更改了文件名,并添加了一些数据,对此感到抱歉。
// file 1: index.js
(async () => {
const common = require('./common')
const actions = require('./actions')
await common.init()
actions.web() //<-- open google.com in browser
})()
// file 2: common.js
const puppeteer = require('puppeteer')
let common = {}
common.init = async () => {
common.browser = await puppeteer.launch({
headless: false,
slowMo: 50 // slow down by 50ms
//devtools: true
})
common.page = await common.browser.newPage()
}
module.exports = common
// file 3: actions.js
const common = require('./common')
let actions = {}
actions.web = async () => {
await common.page.goto('https://google.com', {
waitUntil: 'networkidle2'
})
}
module.exports = actions