Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda