'I get different instances of the same singleton object when imported through different modules in Node.js?
I have module A that uses a singleton pattern to create an object which needs to be shared.
A.js:
...
let instance = undefined;
module.exports {
init: function () {
if(!instance)
instance = new Instance();
},
getSomeValue: function () {
return instance.get();
},
};
I've got two different modules B and C, where each depends on the same module A,
B.js
const { init, getSomeValue } = require('A');
function middleware1(req, res, next) {
init();
next();
}
module.export = middleware1;
C.js
const { getSomeValue } = require('A');
function middleware2(req, res, next) {
console.log(getSomeValue()); // throws undefined, can not recognise initialisation by B module
next();
}
module.export = middleware2;
main application:
...
app.use(middleware1());
app.use(middleware2());
...
but there are separate copies of that dependent module under the node_modules subdirectory of each of the two different modules.
I want to initialize instance once no matter from which library/module it is instantiated and want to share the object across all the libraries/modules using it under the same project.
How can I access the instance state that I want to share across the complete node project?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
