Quantcast
Viewing latest article 19
Browse Latest Browse All 41

Answer by hurrymaplelad for nodejs: Node modules vs singleton classes

Check out Node's module caching caveats for the cases where the 'singletoness' of modules will break down.

If you always reference your singleton module with file paths (starting with ./, ../, or /) within a single package you're safe.

If your service is wrapped up in a package to be used by other modules, you may end up with multiple instances of your singleton.

Say we publish this sweet service library:

service-lib/⌞ package.json⌞ service.jsservice.js:  var singleton = {};  module.exports = singleton;

In this app, server.js and other.js will get different instances of our service:

app/⌞ server.js⌞ node_modules/⌞ service-lib/⌞ service.js⌞ other-package/⌞ other.js⌞ node_modules/⌞ service-lib/⌞ service.js

While this app will share an instance:

app/⌞ server.js⌞ node_modules/⌞ service-lib/⌞ service.js⌞ other-package/⌞ other.js

The same npm installing the same app could result in either directory structure depending on the versions of the dependencies. Node's folders doc has the details.


Viewing latest article 19
Browse Latest Browse All 41

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>