Richeve Bebedor
Richeve Bebedor

Reputation: 1658

NodeJS Require function

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?

Upvotes: 2

Views: 861

Answers (2)

josh3736
josh3736

Reputation: 144882

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.

Upvotes: 5

Manoj Gupta
Manoj Gupta

Reputation: 628

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.

Upvotes: 0

Related Questions