I'm getting inconsistent results when passing objects between modules in a Node JS application, or probably just misunderstanding what is going on!
In my app, written out in pseudo-code below, a lib file is first required into the application root, followed by the other services used by the application, which also require in the same library. The library is then configured in the application root - this sets a class variable (this.foo
) which was initialized as an empty object in the library - and finally a method in one of the services is called.
The foo property is destructured at the top of the service file and if I log it out straight away I get an empty object (as expected). When I call the service method, after foo has been configured elsewhere, and reference the destructured property I still get an empty object. If instead, I don't destructure the property and just require in the library (Lib
), then in the method I access Lib.foo I see the configured value (i.e. as expected).
My suspicion is that the destructured variable is a value that is not being updated and the required library is a reference, but everything I've read suggests that nothing is passed by value. Any pointers would be appreciated!
// main.js
// ========
const lib = require('./lib');
const service = require('./service');
lib.configure({ foo: "bar"});
service.run();
// service.js
// ========
const Lib = require('./lib'); // This is for the example only
const { foo } = require('./lib'); // I'd prefer to just do this
console.log(Lib.foo); // {} as expected
console.log(foo); // {} as expected
class Service {
run() {
console.log(foo); // {} - should be "bar"
console.log(Lib.foo) // "bar" as expected
}
}
module.exports = new Service();
// lib.js
// ======
class Lib {
constructor() {
this.foo = {};
}
configure({ foo }) {
this.foo = foo;
}
}
module.exports = new Lib();