Understanding Node.js modules: multiple requires return the same object?

If both app.js and b.js reside in the same project (and in the same directory) then both of them will receive the same instance of A. From the node.js documentation:

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


The situation is different when a.js, b.js and app.js are in different npm modules. For example:

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

In that case the require('a') in app.js would resolve to a different copy of a.js than require('a') in b.js and therefore return a different instance of A. There is a blog post describing this behavior in more detail.

Leave a Comment