[ACCEPTED]-'Global' object in node.js-node.js

Accepted answer
Score: 13

As of NodeJS v0.8.14 global seems to work 2 across modules like the window object does 1 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
Score: 11

Apparently, the global object isn't the global 6 object as window is in the browser. It's (according 5 to micheil in #nodejs @ freenode) really 4 only used internally. Something about global 3 closures and whatnot.

parseInt and setTimeout and all those 2 buddies are globals on their own. Not part 1 of any visible global object.

Score: 9

Defining variable in app.js without var, just like 2 myvar='someval' makes it visible inside every .js in your 1 project

Score: 0

FAILS:

if( global[ some_object_i_want_to_exist ] ){ ... }

WORKS:

//: outside of all functions, including IIFE.
const THE_GLOBAL_YOU_PROBABLY_WANT_IS_THIS=( this );

//: Within a function:
const G = THE_GLOBAL_YOU_PROBABLY_WANT_IS_THIS;
if( G[ some_object_i_want_to_exist ] ){ ... }

I am assuming you got to this page about 17 "global" in node.js because you 16 wanted the equivalent of "window" in 15 order to check for globally declared variables. bFunc's 14 solution didn't work for me, as it seems 13 to require that one explicitly does something 12 like:

global.some_object_i_want_to_exist = whatever;

as a pre-requisit to using

global[ some_object_i_want_to_exist ]

EDIT: Looking 11 at my code it seems that the only reason 10 my solution worked is because I used "exports.some_object_i_want_to_exist" somewhere 9 else in the file. Without that, my solution 8 fails. So... I have no clue how to reliable 7 determine if an object exists in a given 6 scope in Node.js.

Here is the documentation 5 on global object: https://nodejs.org/api/globals.html

I am going to leave my 4 answer here because I hear people are more 3 likely to correct you when you are wrong, so 2 maybe someone will correct me with the answer 1 to the problem.

More Related questions