I'm running to the following issue with Node.js v0.10.1 (demonstrated with a quick example):
While running node in the interactive command line:
> global.require
{ [Function: require] . . . }
> require
{ [Function: require] . . . }
When running the following script.js I get unexpected results:
console.log(global.require); // 1.
console.log(require); // 2.
undefined // 1. `global.require` is undefined!
{ [Function: require] . . .} // 2. `require` by itself works however.
I've removed extra code denoted by .... Run it locally to see the full extent of what is actually shown.
What causes this to happen?
Node.js contains a repl module that allows you to create your own Read-Evaluate-Print-Loops (this is what repl stands for). Using this module there is a function start that you use to create a new repl.
This function takes an options object where you can configure your repl. One of these options is called useGlobal. According to the documentation for this option the following sentence is valid:
if set to
true, then the repl will use theglobalobject, instead of running scripts in a separate context. Defaults tofalse.
Now when you start Node.js in interactive mode, this is basically nothing but a repl like those you could create for yourself using the repl module. I guess (and please note that this is only a guess!) that Node.js's default repl has useGlobal set to true.
Hence you have a global object, which is in turn the very same as the global namespace anyway. Hence all the functions such as require that you can find on the global namespace you will again find on the global object.
Once you start a Node.js application in non-interactive mode, there is no repl, hence there is no global object.
Does that make sense to you?
Many of the Globals won't normally be in the global scope or members of the global object:
These objects are available in all modules. Some of these objects aren't actually in the global scope but in the module scope - this will be noted.
These are "globals" more by the 2nd interpretation:
Also, as noted for require():
To require modules. See the Modules section.
requireisn't actually a global but rather local to each module.
The REPL module, that manages the interactive mode, has an option to promote them to the global scope:
useGlobal- if set totrue, then the repl will use theglobalobject, instead of running scripts in a separate context. Defaults tofalse.