Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Over-use of require() in node.js, mongoose

I'm new to Node.js, but quite like the module system and require(). That being said, coming from a C background, it makes me uneasy seeing the same module being require()'d everywhere. All in all, it leads me to some design choices that deviate from how things are done in C. For example:

  • Should I require() mongoose in every file that defines a mongoose model? Or inject a mongoose instance into each file that defines a model.
  • Should I require() my mongoose models in every module that needs them? Or have a model provider that is passed around and used to provide these models.

Ect. For someone who uses dependency injection a lot - my gut C feeling is telling me to require() a module only once, and pass it around as needed. However, after looking at some open-source stuff, this doesn't seem to be Node way of things. require() does make things super easy..

Does it hurt to overuse this mechanism?

like image 300
Colin Avatar asked Aug 01 '13 18:08

Colin


1 Answers

require() caches modules when you use it. When you see the same file or module required everywhere it's only being loaded once, and the stored module.exports is being passed around instead. This means that you can use require everywhere and not worry about performance and memory issues.

like image 103
cptroot Avatar answered Sep 20 '22 01:09

cptroot