6

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?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237

1 Answers1

5

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.

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • 2
    I took a different path trying to figure this out, and I found your missing piece [here](https://nodejs.org/api/globals.html#globals_require) - `require` does come from the module context. – Amit Jan 02 '16 at 14:01