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?
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.
stdin
will execute this code, which, as you can see here, will define global.require
;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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With