Nodejs: Node modules versus singleton classes

PRE: I read NodeJS modules against classes , but this is more specific.

As part of some refactoring in Node, I have a couple of applications (in DDD terminology) that are technically implemented as Node modules.

Since (in the DDD world, perhaps, in any other case) Application Services should be single-point, and since Node modules are guaranteed to have only 1 instance, it seems to me that this is normal (modules trivially implement "monotony")

Is there any reason why I should consider reorganizing these applications as valid singleton classes (since "singletonness" can be guaranteed in javascript) other than the purist's point of view?

+5
source share
1 answer

Check out Node module caching warnings for cases where a “single error” of modules will break.

If you always reference your single module with file paths (starting with ./, ../or /) in one package, you are safe.

If your service is wrapped in a package that will be used by other modules, you may encounter multiple instances of your singleton.

Let's say we publish this sweet library of services:

service-lib/package.json
⌞ service.js

service.js:
  var singleton = {};
  module.exports = singleton;

In this application, server.jsthey other.jswill receive different instances of our service:

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

For now, this application will share with the instance:

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

npm install app . Node doc .

+6

All Articles