如何在入口点上要求模块在 NodeJS 上的其他模块上可用?

How requiring a module on entry point makes available on other modules on NodeJS?

这可能是一个重复的问题,但我找不到任何内容。 由于我正在学习NodeJS,我认为我没有使用正确的词来搜索,所以很难找到答案。

情况如下:

我目前正在学习有关 NodeJS 和编码 API 的在线课程。 在当前步骤中,我们使用 Winston 库来记录错误。讲师已经在应用程序的入口点 Index,js 上进行了配置,如下所示:

文件:index.js

const winston = require('winston');
const errorHandler = require(./middleware/error.js);
//(...) some other imports
app.use(errorHandler);

winston.add(winston.transports.File,{filename:'logFile.log'});

而在我们在课程中创建的其他处理错误的模块中,他需要 winston 并简单地调用以记录错误。像这样:

文件:error.js

const winston = require('winston');

function errorHandler(err,req,res,next){
    winston.error(err.message,err);
    res.status(500).send("something failed");
}

module.exports = errorHandler;

经过测试,错误正确地写入了文件,我的问题是:它是如何工作的? index.js 的 winston 'required version' 上的设置如何从 error.js 的其他所需版本可见?

我们也在从 index.js 导入 error.js,所以我可以想象这两个模块以某种方式共享这个 winston 对象,但同样,我不明白它是如何共享的或在何处共享。

再一次,如果我没有使用正确的术语来引用这里的任何内容,请原谅,我会接受任何建议。

谢谢。

当模块在 node.js 中加载时,它会被 require() 子系统缓存。因此,当您再次 require() 时,这意味着您将获得与前一个完全相同的模块。

所以...如果您在第一次加载模块后对其进行了初始化,并且该模块存储了一些表示该初始化的状态,那么该模块的后续使用将使用相同的(已经初始化的)模块。

And in other module we've created in the course to handle errors, he requires winston and simply call to log the error.

它获取与之前 initialized/configured 相同的 winston 模块实例。

After doing a test, the error is correctly written to the file, and my question is: How it works? How a setting made on the 'required version' of winston at index.js is visible from the other required version at error.js?

如上所述的模块缓存。只有一个 winston 模块所有人共享,因此如果它在一个地方 initialized/configured,所有人都将使用该配置。