Reputation: 81
I want to make "variable sharing" in node.js but I cannot find a working way to do that.
My aim is to be able to change variables from an another file. For example, I have a
in my main file but after doing something in another file (test.js
), a
should change its value in the main file. Is it possible to accomplish and how?
I have tried this code but it does not seem to work.
main.js
let a = 10;
module.exports.test = a;
console.log(a);
require('./test.js');
console.log(a);
test.js
let b = require('./main.js').test;
b = 15;
Upvotes: 1
Views: 4474
Reputation: 707158
Other answers given here suggest using globals, but you should avoid use of globals for a whole host of reasons which I won't go into here, but are well documented.
The modular and safe way to share data is to put it in an object (as properties of an object) and then export that object from one module and import it into any others that want access to it. Since the exported object is truly shared, any update to any property on that object will be immediately available to all others who have a reference to the same object.
shared-data.js
module.exports = {a: 10};
test.js
let obj = require('./shared-data.js');
++obj.a;
main.js
let obj = require('./shared-data.js');
console.log("main1: ", obj.a);
++obj.a;
console.log("main2: ", obj.a);
require('./test.js');
console.log("main3: ", obj.a);
This will output:
main1: 10
main2: 11
main3: 12
Because test.js is operating on the shared data that shared-data.js exports
Upvotes: 5
Reputation: 15177
The bad idea here is think when you call ./test
, magically variable a
will be updated.
Here you can use global
variables (example)
Something like:
main.js
global.a = 10
//call test
console.log(global.a)) // 15
test.js
global.a = 15
And, following you idea, calling another class and using these values, you can also do something like this:
main.js
var a = 10
a = require('./test').a //Note that here you are overwriting your 'a' variable
console.log(a) //15
test.js
var b = 15
module.exports.a = b
So, into main.js
you assign a
value that is from module.exports.a
, i.e. you assing a = 15
.
Upvotes: 0
Reputation: 1
You can just use global variables. See more here
main.js
global.a = 10;
console.log(global.a); // 10
require('./test.js');
console.log(global.a); // 15
test.js
console.log(global.a) // 10
global.a = 15
Upvotes: 0