6

I am trying to organize a Node.js application developed with Express 4 and am confused about the scope of modules which are imported with require().

Imagine that I use require('./services/user') to import a service in a module such as routes/user.js:

var userService = require('./services/user');

Then I do the same require('./services/user') in another module routes/department.js.

My question is: is userService the same instance in user.js and department.js or each of them has it's own userService object? That is to say, once you've exported some element through module.exports = XXX if you require the same file, will you get always the same instance? Could you show me where in the Node.js docs that's specified?

codependent
  • 23,193
  • 31
  • 166
  • 308

1 Answers1

5

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 user
app.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:

EDIT:

Other helpful links:

node.js require() cache - possible to invalidate?

Community
  • 1
  • 1
DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
  • Thanks! Perfect answer. So if I understood well, as long as there's a common ancestor module all imported modules are catched and shared among all of them? – codependent Sep 25 '14 at 11:09
  • That s right, as long as it s the same instance of node that is started, the required module are shared among all module. – DrakaSAN Sep 25 '14 at 12:08