通过 Node.js 中的不同模块导入时,我会得到同一单例对象的不同实例吗?

发布于 2025-01-15 00:48:54 字数 970 浏览 1 评论 0原文

我有模块 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文