Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 835
Billy Moon Avatar asked Sep 25 '22 19:09

Billy Moon


1 Answers

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.

like image 116
robertklep Avatar answered Oct 11 '22 06:10

robertklep