简体   繁体   中英

Nodejs. Proper way to include modules

I have a server.js file that includes the module puppeteer.

const puppeteer = require('puppeteer');

I want to run a function inside routes.js that uses that module.

async function getPic(arg) {
    const browser = await puppeteer.launch(/*{headless: false}*/);
    const page = await browser.newPage();
    await page.goto(arg);
    await page.setViewport({width: 1000, height: 500})
    await page.screenshot({path: 'pic.png'});

    await broswer.close();
}

When i attempt to run this then it doesn't work because "puppeteer is not defined".

So what is the most optimal way to solve this? Obvisouly i cannot reinclude the puppeteer module in routes.js So do i include the server.js file in routes.js? Or this might cause modules and variables and functions to be instantiated twice? (one time when server.js ran - as it is the starting point, and one time when routes.js ran and reruns server.js)

Write const puppeteer = require('puppeteer'); inside routes.js, this is how Node.js work. Every single module is behaving like singleton, it is executed on first require and then saved into memory. Next require just returns the pointer to this memory (so requiring puppeteer from server.js and routes.js will point to the same object).

require the module in server.js

const puppeteer = require('puppeteer');

You have to require your route.js file in server.js as mentioned below

require('./app/routes.js')(puppeteer); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM