Reputation: 5038
I have a worker.js
file which periodically updates the values of few variables.
In other files of my Node.js server I want to access to those vars.
I know how to export them, but it seems they are exported by value - i.e. they have the value they had at the moment I issued the require
function.
Of course, I'm interested to access to their latest value. What's the recommended way to do this? A "getter" function or else?
Upvotes: 1
Views: 7931
Reputation: 1086
A possible way to export them by reference is to actually manipulate the module.exports
object - like so:
//worker.js
module.exports.exportedVar = 1;
var byValueVar = 2;
setInterval(foo, 2000);
function foo() {
module.exports.exportedVar = 6;
x = 8;
}
//otherfile.js
var worker = require('./worker');
console.log(worker.exportedVar); //1
console.log(worker.byValueVar) //2
setInterval(foo, 3000);
function foo() {
console.log(worker.exportedVar); //6
console.log(worker.byValueVar); //2
}
Upvotes: 2