Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About global variables in Node.js

Node.js seems to use different rules to attach variables to the global object whether this is done in the REPL or in a script.

$ node
> var a = 1;
undefined
> a
1
> global.a
1
> a === global.a
true

As shown above when working in the REPL, declaring a variable with var creates a new property with the name of that variable on the global object.

However, this doesn't seem to be the case in a script:

// test.js

var a = 1;
console.log(a);
console.log(global.a);
console.log(a === global.a);

Let's run the script:

$ node test.js
1
undefined
false

Why is this happening?

like image 740
kYuZz Avatar asked Jan 23 '16 19:01

kYuZz


2 Answers

When a script is run, it is wrapped in a module. The top level variables in a script are inside a module function and are not global. This is how node.js loads and runs scripts whether specified on the initial command line or loaded with require().

Code run in the REPL is not wrapped in a module function.

If you want variables to be global, you assign them specifically to the global object and this will work in either a script or REPL.

 global.a = 1;

Global variables are generally frowned upon in node.js. Instead variables are shared between specific modules as needed by passing references to them via module exports, module constructors or other module methods.


When you load a module in node.js, the code for the module is inserted into a function wrapper like this:

(function (exports, require, module, __filename, __dirname) {
     // Your module code injected here
});

So, if you declare a variable a at the top level of the module file, the code will end up being executed by node.js like this:

(function (exports, require, module, __filename, __dirname) {
      var a = 1;
});

From that, you can see that the a variable is actually a local variable in the module function wrapper, not in the global scope so if you want it in the global scope, then you must assign it to the global object.

like image 152
jfriend00 Avatar answered Sep 28 '22 00:09

jfriend00


There is no window in Node.js but there is another highest object called global.

Whatever you assign to global.something in one module is accessible from another module.

Example:

app.js

global.name = "myName"

now you can get the global.name from any module

myController.js

console.log(global.name);  // output: myName

anotherModule.js

console.log(global.name);  // output: myName

now when you declare a variable at one module var i=0; is it available from all module? NO !

Because all your project code is wrapped under a module, On REPL it doesn't. it's the highest level. That's why REPL variable becomes global.

so if you want to work with global, you have to use with the global prefix

global.a = 1;
console.log(global.a);
like image 42
Ikrum Hossain Avatar answered Sep 28 '22 00:09

Ikrum Hossain