Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Global' object in node.js

I am using 0.3.1-pre Node.js

Doing this:

typeof global.parseInt

results in

'undefined'

However when pressing [Tab] in the console after typing 'global.' gives a list of functions, including parseInt.

So is parseInt a member of the global namespace or not?

like image 691
Art Avatar asked Nov 09 '10 11:11

Art


People also ask

What is global object in node?

A global object is an object that always exists in the global scope. In JavaScript, there's always a global object defined. In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.

What is global variable in node JS?

Global variables are variables that can be declared with a value, and which can be accessed anywhere in a program. The scope of global variables is not limited to the function scope or any particular JavaScript file. It can be declared at one place and then used in multiple places.

What is global object and local object?

Explanation: The object declared outside all function bodies is known as global object. All functions can access the global object. The object declared inside a function body is known as local object. The scope of local object is limited to its current block.

How do I declare global in node JS?

Just because you use the word var at the top of your Node. js script does not mean the variable will be accessible by all objects you require such as your 'basic-logger' . To make something global just put the word global and a dot in front of the variable's name.


1 Answers

As of NodeJS v0.8.14 global seems to work across modules like the window object does in the browser.

Test:

a.js:

a1 = console.log;  // Will be accessed from b.js
global.a2 = console.log;  // Will be accessed from b.js

require('./b.js');

b1('a: b1');
b2('a: b2');
global.b1('a: global.b1');
global.b2('a: global.b2');

b.js:

a1('b: a1');
a2('b: a2');
global.a1('b: global.a1');
global.a2('b: global.a2');

b1 = console.log;  // Will be accessed from a.js
global.b2 = console.log;  // Will be accessed from a.js

Running a.js outputs:

b: a1
b: a2
b: global.a1
b: global.a2
a: b1
a: b2
a: global.b1
a: global.b2
like image 103
zupa Avatar answered Sep 28 '22 18:09

zupa