I was inspecting the global and module of node when I discovered that require was not in them. I don't know if this is magic but if anyone can explain if require is global then why it is not in the global object nor in the module object?
-
please visit this link: http://nodejs.org/api/globals.html – Jyoti Prakash Jan 03 '14 at 05:07
2 Answers
Because it's in scope. When loading in a file, node behind the scenes wraps the source code such that your code actually looks like this:
(function (exports, require, module, __filename, __dirname) {
// here goes what's in your js file
});
It then invokes the anonymous function, passing in a fresh object for exports
and a reference to the require
function. (Further detail here.)
It should now be obvious why you can call require
even though it's not truly a global.
-
-
INTERESTING by wrapping the entire source in an anonymous function things get local only to that and it gives the impression the require is global. Now I understand thank you very much! – Richeve Bebedor Jan 04 '14 at 08:54
Require is Core Modules compiled into the binary. Read in more detail here http://nodejs.org/api/modules.html#modules_core_modules .
The core modules are defined in node's source in the lib/ folder.
Core modules are always preferentially loaded if their identifier is passed to require(). For instance, require('http') will always return the built in HTTP module, even if there is a file by that name.

- 578
- 5
- 10
-
This doesn't really address *why* the identifier `require` is defined even though it does not exist in global scope. – josh3736 Jan 03 '14 at 05:35