I have a question related to 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.
What is meant with may
?
I want to know if require will always return the same object. So in case I require a module A in app.js
and change the exports object within app.js
(the one that require returns) and after that require a module B in app.js
that itself requires module A, will I always get the modified version of that object, or a new one?
// 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');
Best Answer
If both
app.js
andb.js
reside in the same project (and in the same directory) then both of them will receive the same instance ofA
. From the node.js documentation:The situation is different when
a.js
,b.js
andapp.js
are in different npm modules. For example:In that case the
require('a')
inapp.js
would resolve to a different copy ofa.js
thanrequire('a')
inb.js
and therefore return a different instance ofA
. There is a blog post describing this behavior in more detail.