PRE: I've read NodeJS modules vs classes but this is more specific.
As part of some refactoring in Node I have a couple of Application Services (in DDD-terminology) which are technically implemented as Node modules.
Since (in a DDD-world, an probably any other for that matter) Application Services should be singletons and since Node modules are guaranteed to be 1 'instance' only, it seems to me that this is an okay fit (modules trivially implement the 'singletonness')
Is there any reason why I should consider refactoring these application services as proper singleton classes (as far as 'singletonness' can be guarenteed in javascript anyway), apart from the purist standpoint?
Check out Node's module caching caveats for 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.js
service.js:
var singleton = {};
module.exports = singlton;
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.