Billy Moon
Billy Moon

Reputation: 58601

Why does `global.require` return undefined when executed as nodejs script?

If I log global.require by piping script to node, it is a function, but if I run from within script passed to node, it is undefined...

➜  Desktop  cat req.js 
console.log(global.require)
➜  Desktop  cat req.js | node
{ [Function: require]
  resolve: [Function],
  main: undefined,
  extensions: 
   { '.js': [Function],
     '.json': [Function],
     '.node': [Function: dlopen] },
  registerExtension: [Function],
  cache: {} }
➜  Desktop  node req.js 
undefined
➜  Desktop

Have I found Schrödinger's variable - or is there a more mundane explanation?

Upvotes: 6

Views: 810

Answers (1)

robertklep
robertklep

Reputation: 203419

If I understand the Node code correctly:

When Node starts up, there's a few different execution paths that Node can take. In your case, there are two: reading the script from stdin, or reading it from file.

  • reading from stdin will execute this code, which, as you can see here, will define global.require;
  • reading from a file will follow a different code path (starting here) that doesn't define global.require;

Perhaps in the latter case, require is provided by the module context and hence it's not necessary to be added to global, but that's just me guessing.

Upvotes: 5

Related Questions