Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple instances of module in node.js?

Tags:

node.js

In nodejs modules are singletons. I have created a module that takes configuration object and return some object. But at last I will be having single instance of the module. How to have multiple instances for different configurations?(each time they require, it should be different instance. How to achieve this?)

like image 597
Ordre Nln Avatar asked Dec 19 '22 06:12

Ordre Nln


2 Answers

Export a constructor and don't have implicit state:

Your current code looks something like:

module.exports = { ..}; // some object

Instead export a constructor:

module.exports = function(){
    // initialize module here, no global variables
    return { .. };
};
like image 75
Benjamin Gruenbaum Avatar answered Jan 10 '23 06:01

Benjamin Gruenbaum


Return only constructors and have a dedicated module for the singletons:

lib/user.js:

module.exports = function () { ... }

lib/currentUser.js:

module.exports = new (require('./user'))();
like image 31
avetisk Avatar answered Jan 10 '23 06:01

avetisk