Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'require' is not defined in console tab of node-inspector's repl

I tried to

require('fs').writeFileSync('o.json', JSON.stringify(anObject));

for debugging, and I got RefrenceError: require is not defined.

This is bizarre. What kind of an environment is it that doesn't have require?

like image 801
user3025492 Avatar asked Nov 29 '13 10:11

user3025492


1 Answers

In Node.js, the require function is not defined globally. When you require a module, its source code is wrapped by a function that takes several arguments and require is one of them:

(function (exports, require, module, __filename, __dirname) {/* your code */
});

You can see that wrapper in Node Inspector when you look at the content of any source file.

Now there are two different scenarios for evaluating code from Node Inspector's console:

  1. The debugged process is running. Expressions are evaluated in the global context, i.e. you have access only to globally defined symbols. require is not among them.

  2. The debugged process is paused on a break point. The expression is evaluated in the context of the select stack frame and have access too all variables in the current scope (which include variables captured by closures from by outer functions). However: most functions don't call require, therefore this variable is not captured in any closure and you can't access it.

I had a short chat with one of the Node core developers about exposing require as a global symbol, because it would simplify injecting code from Node Inspector, but my arguments were not convincing enough.

like image 173
Miroslav Bajtoš Avatar answered Nov 15 '22 04:11

Miroslav Bajtoš