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?)
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 { .. };
};
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'))();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With