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 install
ing the same app
could result in either directory structure depending on the versions of the dependencies. Node's folders doc has the details.