通过 Node.js 中的不同模块导入时,我会得到同一单例对象的不同实例吗?
我有模块 A,它使用单例模式来创建需要共享的对象。
A.js:
...
let instance = undefined;
module.exports {
init: function () {
if(!instance)
instance = new Instance();
},
getSomeValue: function () {
return instance.get();
},
};
我有两个不同的模块 B 和 C,其中每个模块都依赖于同一个模块 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());
...
但是在两个不同模块的 node_modules 子目录下都有该依赖模块的单独副本。 我想初始化实例
一次,无论它是从哪个库/模块实例化的,并且希望在同一项目下使用它的所有库/模块之间共享该对象。
如何访问我想要在整个节点项目中共享的实例
状态?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论