Sombriks
Sombriks

Reputation: 3622

Avoiding re-evaluation and dynamically unloading objects called with `require`

i'm studying how nodejs module system works.

I've found so far this literature:

  1. https://nodejs.org/api/modules.html
  2. http://fredkschott.com/post/2014/06/require-and-the-module-system/
  3. http://www.bennadel.com/blog/2169-where-does-node-js-and-require-look-for-modules.htm

It helps me to understand a few points however is still have these questions:

It's important because i have some scenarios that demands me to make sure that i have a single instance of database pool. because of this i'm exporting modules which are able to receive parameters instead of just require the expensive resource.

Any guidance is very appreciated.

Upvotes: 1

Views: 93

Answers (1)

Chad Robinson
Chad Robinson

Reputation: 4623

Alon Salont has written an EXCELLENT guide to understanding exports in NodeJS (which is what you're accessing when you call require()) here: http://bites.goodeggs.com/posts/export-this/#singleton

If you study the list of options for what a module can export, you'll see that the answer to your question depends on how the module is written. When you call require, NodeJS will look for the module loaded in its cache and return it if it already had it loaded elsewhere.

That means if you choose to export a Singleton pattern, are monkey-patching, or creating global objects (I recommend only the first one in your case), only ONE shared object will be created / will exist. Singleton patterns are good for things like database connections that you want to be shared by many modules. Although some argue that "injecting" these dependencies via a parent/caller is better, this is a philosophical view not shared by all, and singletons are widely used by software developers for shared-service tasks like this.

If you export a function, typically a constructor, require() will STILL return just one shared reference to that. However, in this case, the reference is to a function, not something the function returns. require() doesn't actually CALL the function for you, it just gives you a reference to it. To do any real work here, you must now call the function, and that means each module that requires this thing will have its own instance of whatever class the module provides. This pattern is the more traditional one where a class instance is desired / is the goal. Most NPM modules fit this category, although that doesn't mean a singleton is a bad idea in your case.

Upvotes: 1

Related Questions