Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs: Node modules vs singleton classes

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?

like image 302
Geert-Jan Avatar asked Jul 31 '12 17:07

Geert-Jan


People also ask

Are Nodejs modules singleton?

Node. js modules can behave like Singletons, but they are not guaranteed to be always singleton.

Is a module a singleton?

Modules are “singletons” in Python because import only creates a single copy of each module; subsequent imports of the same name keep returning the same module object.

CAN module be used with singleton?

In javascript we can use module as singleton.

What is the disadvantages of using singleton?

Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.


1 Answers

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.js

service.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.

like image 174
hurrymaplelad Avatar answered Oct 13 '22 11:10

hurrymaplelad