node.js - 了解 Node.js 模块 : multiple requires return the same object?

标签 node.js

我有一个与 the node.js documentation on module caching 相关的问题:

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

可以是什么意思?

我想知道 require 是否会总是返回相同的对象。因此,如果我需要 app.js 中的模块 A 并更改 app.js 中的导出对象(需要返回的对象)和之后在 app.js 中需要一个模块 B 本身需要模块 A,我会总是得到修改吗该对象的版本,还是新版本?

// app.js

var a = require('./a');
a.b = 2;
console.log(a.b); //2

var b = require('./b');
console.log(b.b); //2

// a.js

exports.a = 1;

// b.js

module.exports = require('./a');

最佳答案

如果两者都是 app.jsb.js驻留在同一个项目(并且在同一个目录中),那么他们都会收到相同的实例 A .来自 node.js documentation :

... every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.


a.js 时情况有所不同, b.jsapp.js位于不同的 npm 模块中。例如:

[APP] --> [A], [B]
[B]   --> [A]

在这种情况下,require('a')app.js将解析为 a.js 的不同副本比 require('a')b.js并因此返回 A不同实例 .有一个blog post更详细地描述此行为。

关于node.js - 了解 Node.js 模块 : multiple requires return the same object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8887318/

相关文章:

javascript - 为什么 JavaScript "this"在 Node 和 Browser 环境中返回不同的值?

node.js - Sequelize.js 中的前缀支持

node.js - 在没有 Express 的情况下将变量传递给 Jade

node.js - 如何修复 Invalid multipart request with 0 mime parts 错误

javascript - multer 单个上传不起作用,但数组可以工作

html - 使用 websockets 和 node.js 的 Web 应用程序

javascript - 契约JS : how to publish to a pact-broker

javascript - 无法读取未定义的属性 'includes'

javascript - 设置雷达图标记的颜色

javascript - 类型错误 : Date is not a constructor in Node js