Gianni Azizi
Gianni Azizi

Reputation: 250

How to avoid singleton in node

I have an npm dependency that I import into a file of my server node. I wish it was not a singleton because it should not be shared between each request.

The file who import the dependency :

const dependency = require('dependency');

export class dependencyFactory {

  public static getDependency() {
    return dependency;
  }

}

index.js of dependency in node_modules :

const path = require('path');
const createApi = require('./createApi');

module.exports = createApi(path.join(__dirname, './lib/providers'));

How can i do that ? thank you.

Upvotes: 1

Views: 874

Answers (1)

Estus Flask
Estus Flask

Reputation: 222875

Modules result in singletons in Node. If this is undesirable, a workaround always depends on specific package.

A preferable way is to export factory function or constructor class from a package that can create new instances when needed.

If this is not possible, possible workarounds may include:

  • use package internal modules to create new instances
  • invalidate module cache to re-import a package
  • get class constructor from a singleton and create a new instance

All of them can be considered hacks and should be avoided when possible. E.g. relying on internal package structure may introduce breaking changes with new package version, even if package changelog doesn't assume breaking changes. And a pitfall for cache invalidation is that a package may consist of numerous modules that should or should not be re-imported.

The first workaround seems to be applicable here.

const createApi = require('dependency/createApi');
const instance = createApi(require.resolve('dependency/lib/providers'));

A cleaner solution is to fork a package and add a capability to create multiple instances.

Upvotes: 1

Related Questions