Skip to content Skip to sidebar Skip to footer

What's The Global Object Within A Module In Nodejs?

I know in node, every module gets an local scope and variable defined within one module won't escape to the global unless explicitly exported. What I want to know is when I declare

Solution 1:

There is in fact a global object in node; it's simply called global. You can assign properties to it and access those properties just like any other object, and you can do it across modules. However, directly accessing it (global.foo=bar in one module, baz=global.foo in another) is the only way to access it. Unqualified variable names never automatically resolve to its properties the way that, say, an unqualified variable name in a browser environment would resolve to window.somethingOrOther. In node, every module is conceptually wrapped inside an immediate function call, so unqualified names represent local variables and have module-level scope.

Solution 2:

edit again I'm just about ready to conclude that, in a Node module, you can't get a reference to the global object. You really shouldn't need to; that's kind-of the whole point of the module mechanism, I think. You import what you need and export what you choose.

Whether there even is a global object in Node is an interesting question, I guess. I know that in Rhino, there definitely is; there's no implicit wrapper function around code fed to Rhino from the Java container. Via the Java ScriptEngine mechanism (and presumably from Mozilla APIs in "naked" Rhino) there are ways of pushing symbols into the global context to make them visible to JavaScript as global object properties.

wow this got complicated well things seem to be on the move in the Node.js world. What I wrote above was true for Node 0.6.2, but in the 0.9.0-pre build I just did there is indeed an object called "global" that behaves more or less like the global object in a browser.


The stuff below applies to browsers and Rhino and other contexts like that

You can use this in the global context. If you need a name, you can give it one.

varglobal = this;

var obj = "Hi!";

global.obj = "Bye"; // sets "obj"

A (somewhat) common idiom is to wrap your code in a function, to protect the global namespace.

(function(global) {
  // everything
})( this );

Caveat: I'm not a Node person so there may be some emerging idiom in that culture.

edit — it occurs to me that if Node really does wrap code from files it evaluates in a function, and it doesn't pass this into it from the global context, then there's no way to "find" it, I don't think. If you use "use strict" (and you should), it doesn't matter, because you can't really mess with the global context anyway.

Post a Comment for "What's The Global Object Within A Module In Nodejs?"