Use variables between files in Node.js?

Here are 2 files:

// main.js require('./modules'); console.log(name); // prints "foobar" // module.js name = "foobar"; 

When I don't have "var", it works. But when I have:

 // module.js var name = "foobar"; 

the name will be undefined in main.js.

I have heard that global variables are bad, and it is better to use "var" before references. But is this the case when global variables are good?

+76
javascript global-variables
Oct 13 '10 at 11:11
source share
4 answers

Global variables are almost never good (maybe an exception or two there ...). In this case, it looks like you really want to export your name variable. For example.

 // module.js var name = "foobar"; // export it exports.name = name; 

Then in main.js ...

 //main.js // get a reference to your required module var myModule = require('./module'); // name is a member of myModule due to the export above var name = myModule.name; 
+129
Oct 13 2018-10-10
source share
โ€” -

If we need to use several variables, use the format below

 //module.js let name='foobar'; let city='xyz'; let company='companyName'; module.exports={ name, city, company } 

Using

  // main.js require('./modules'); console.log(name); // print 'foobar' 
+2
Oct 21 '17 at 16:26
source share

a variable declared with or without the var keyword is bound to a global object. This is the basis for creating global variables in Node by declaring variables without the var keyword. Although the variables declared with the var keyword remain local to the module.

see this article for further understanding - https://www.hacksparrow.com/global-variables-in-node-js.html

0
Jun 29 '17 at 12:41 on
source share

To exchange a variable between a module, you can use the function to get the value of a variable between the main and modules.

 //myModule.js var mainFunction = null; //You can also put function reference in a Object or Array function functionProxy(func){ mainFunction = func; //Save the function reference } // --- Usage --- // setTimeout(function(){ // console.log(mainFunction('myString')); // console.log(mainFunction('myNumber')); // }, 3000); module.exports = { functionProxy:functionProxy } 

.

 //main.js var myModule = require('./myModule.js'); var myString = "heyy"; var myNumber = 12345; function internalVariable(select){ if(select=='myString') return myString; else if(select=='myNumber') return myNumber; else return null; } myModule.functionProxy(internalVariable); // --- If you like to be able to set the variable too --- // function internalVariable(select, set){ // if(select=='myString'){ // if(set!=undefined) myString = set; // else return myString; // } // else if(select=='myNumber'){ // if(set!=undefined) myNumber = set; // else return myNumber; // } // else return null; // } 

You can always get the value from main.js even when changing the value.

0
Jul 02 '17 at 9:24 on
source share



All Articles