Node.js - What's the scope of the require()d modules?
If I understand your question correctly, you have theses files:
.|_. app.js|_. routes/ |_. user.js |_. department.js |_. services/ |_. user
And your code do this:
app.js call user.js user.js call userapp.js call department.js department.js
In that case, at the first time user is required, it is put on cache in require.cache
.
Then the second time it is called, the caller get require.cache['./service/user']
, where is stored your object.
As such, you do have the same object in both department.js and user.js.
Source:
- http://nodejs.org/docs/latest/api/modules.html#modules_caching
- http://nodejs.org/docs/latest/api/modules.html#modules_cycles (helped me understand)
- Understanding Node.js modules: multiple requires return the same object?
- Self modifying code in node.js, would cluster work? (about require.cache)
EDIT:
Other helpful links: