简体   繁体   English

的NodeJS。 包含模块的正确方法

[英]Nodejs. Proper way to include modules

I have a server.js file that includes the module puppeteer. 我有一个包含模块puppeteer的server.js文件。

const puppeteer = require('puppeteer');

I want to run a function inside routes.js that uses that module. 我想在使用该模块的routes.js中运行一个函数。

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". 当我试图运行它然后它不起作用,因为“puppeteer没有定义”。

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? 显然我无法在routes.js中重新包含puppeteer模块所以我在routes.js中包含了server.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) (有一次当server.js运行时 - 因为它是起点,有一次是在routes.js运行并重新运行server.js时)

Write const puppeteer = require('puppeteer'); const puppeteer = require('puppeteer'); inside routes.js, this is how Node.js work. 在routes.js中,这就是Node.js的工作方式。 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). 接下来只需返回指向此内存的指针(因此需要来自server.js的puppeteer和routes.js将指向同一个对象)。

require the module in server.js 需要server.js中的模块

const puppeteer = require('puppeteer');

You have to require your route.js file in server.js as mentioned below 你必须在server.js中要求你的route.js文件,如下所述

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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