0

I have a server.js which looks like:

var app1 = require('./app1.js'); app1.start(); var app2 = require('./app2.js'); app2.start(); 

Now I have a common.js that is used in in both app1.js and app2.js.

So in app1.js I have:

var common = require('./common.js'); 

and in app2.js I have:

var common = require('./common.js'); 

I'm wondering if this is ok to do this. Does node use the same reference in both these situations, or is it duplicated?

5
  • Yes, that’s fine, and they’ll be the same object (though it’s not generally good design to count on that last part). Commented Sep 5, 2017 at 3:39
  • @Ryan Why should I not count on that part? If that was not the behavior, then most of the internet would come crashing down. Commented Sep 5, 2017 at 3:41
  • Node caches requires, so it really doesn't matter how many times you require it Commented Sep 5, 2017 at 3:46
  • Related answer from just a few hours ago: Using inline require called multiple times Commented Sep 5, 2017 at 4:08
  • @torazaburo: If you were relying on it, it would mean you were relying on singletons/stateful modules, which tend to be bad ideas. Commented Sep 5, 2017 at 4:34

2 Answers 2

5

Yes, it is absolutely fine to do this. require() essentially includes the contents of the target page on the current page. If you need to use the modules on multiple pages, you will need to use require() on each page.

var common = require('./common.js') will result in the variable common having the exact same structure as whatever is returned by module.exports in common.js. In fact, they'll be the exact same object.

There's some great documentation regarding this at SitePoint.

Hope this helps! :)

Sign up to request clarification or add additional context in comments.

Comments

1

It is okay. However, they do use the same references which is cached by node. So try not to mutate the required files by mutating object properties, otherwise you may encounter some unexpected behavior.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.