我有一个与 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.js
和 b.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.js
和 app.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/