1

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;
Fortnite
  • 81
  • 2
  • 6

3 Answers3

5

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

Peter O.
  • 32,158
  • 14
  • 82
  • 96
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

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
  • Globals are not recommended in nodejs as it wrecks various goals of modules (like the ability to test a module independently), particularly when data can be shared in a modular way just fine that doesn't have the drawbacks of globals. – jfriend00 Jan 10 '21 at 19:35
0

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.

J.F.
  • 13,927
  • 9
  • 27
  • 65
  • Globals are not recommended in nodejs as it wrecks various goals of modules (like the ability to test a module independently), particularly when data can be shared in a modular way just fine that doesn't have the drawbacks of globals. – jfriend00 Jan 10 '21 at 19:35