Larry Lawless
Larry Lawless

Reputation: 623

Why is global.module undefined within a file but in the Node REPL it is an object on global?

If I:

console.log(global.module);

within a file foo.js and execute it with:

node foo.js

It outputs undefined. However if I access the same property on the global object when I launch the Node REPL it is an object. The same actual object that get's passed as an argument to a modules wrapper function, module.

Why is it not present within a file on the global object but it is in the REPL?

Upvotes: 1

Views: 215

Answers (1)

Alexander O'Mara
Alexander O'Mara

Reputation: 60577

In the context of a module file, module is not a global variable, it is actually a local variable. Node module code is actually wrapped in code like this before execution:

(function (exports, require, module, __filename, __dirname) { 

All of these variables must be unique to each module, so they cannot be global variables.

In REPL and other code that gets evaluated in the global scope however, these variables get added as properties of the global object so you can still use things like require.

Upvotes: 1

Related Questions