Node.js需要一次还是多次?

Node.js require once or multiple times?

我有这 2 个文件:

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;

代码运行到“Request.get(...)”。控制台显示此错误:
ReferenceError:请求未定义”。

现在,我是 Node.js 的新手,所以我想问的是:我是否每次都需要相同的模块用于我使用它的所有 .js 还是有一种方法可以整个需要它一次应用程序?

您需要它的所有文件中都必须要求它。所以把它添加到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?

require 在本地加载每个模块,因此您必须在每个需要模块的 .js 文件中使用 require

来自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. It accepts a single argument. It is not global but rather local to each module.