Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

227
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!