Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

228
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda