Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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

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

Problem

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?

Problem courtesy of: Colin

Solution

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.

Solution courtesy of: cptroot

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

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

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×