簡體   English   中英

如何在Node.js中的多個文件中拆分代碼?

[英]How to split code in multiple files in Node.js?

我正在嘗試將我的代碼拆分為多個文件,但無法正常工作,我不確定為什么。

我有3個文件,main.js,common.js和doSomething.js。 common.browser是chrome實例,因此重要的是它只能啟動一次,並且我可以從每個文件訪問它。

在下面的代碼中,它不起作用。 common.browserdoSomething.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 ,則必須給common提供一個構造函數並實例化它。

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();

我正在測試解決方案,但出現錯誤。 我可以通過在文件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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM