[英]Node.js require once or multiple times?
I have this 2 files:我有这两个文件:
const Request = require('request'); const YVideo = require('./classes/YVideo'); const yvideo = new YTVideo();
class YVideo { constructor(uuid){ this.uuid = uuid; this.url = 'https://example.com/get_video_info?uuid='; Request.get(this.url+this.uuid, function(err, resp, body){ this.data = body.split('&'); }); console.log(this.data); } } exports = module.exports = YTVideo;
The code runs until " Request.get(...) ".代码运行直到“ Request.get(...) ”。 Console shows this error:
控制台显示此错误:
" ReferenceError: Request is not defined ". “参考错误:请求未定义”。
Now, I'm new with Node.js, so what I ask is: Should I require the same module each time for all .js where I use it or there's a way to require it once for entire app?现在,我是 Node.js 的新手,所以我要问的是:我是否应该每次都为使用它的所有 .js 需要相同的模块,或者有一种方法可以为整个应用程序要求一次?
It has to be required in all the files where you need it.在您需要它的所有文件中都必须需要它。 So add it in YVideo file where it is needed.
所以将它添加到 YVideo 文件中需要它的地方。
const Request = require('request');
class YVideo {
constructor(uuid){
this.uuid = uuid;
this.url = 'https://example.com/get_video_info?uuid=';
Request.get(this.url+this.uuid, function(err, resp, body){
this.data = body.split('&');
});
console.log(this.data);
}
}
exports = module.exports = YTVideo;
Question: Should I require the same module each time for all .js where I use it or there's a way to require it once for entire app?
问题:我应该每次都为我使用它的所有 .js 需要相同的模块,还是有一种方法可以为整个应用程序需要一次?
require
locally loads each module, so you will have to use require
in every .js
file you need the module. require
在本地加载每个模块,因此您require
在需要该模块的每个.js
文件中使用require
。
From https://www.w3resource.com/node.js/nodejs-global-object.php来自https://www.w3resource.com/node.js/nodejs-global-object.php
The require() function is a built-in function, and used to include other modules that exist in separate files, a string specifying the module to load.
require() 函数是一个内置函数,用于包含存在于单独文件中的其他模块,一个字符串指定要加载的模块。 It accepts a single argument.
它接受一个参数。 It is not global but rather local to each module.
它不是全局的,而是每个模块本地的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.