0

I use chrome devtools to debug node.js script (node --inspect script.js, as described e.g. in https://nodejs.org/en/docs/guides/debugging-getting-started/)

For some reason a function statement is not working properly. This is the code:

function f(){};
f=1;
console.log(f);

http = require('http');
myserver=http.createServer(function (req, res) {
    res.end();
}).listen(8080);

The console outputs 1, but then when I try to enter f in the console it says "Uncaught ReferenceError: f is not defined".

If instead of a function statement I use function expression, everything works well:

f=function(){};
f=1;
console.log(f);

http = require('http');
myserver=http.createServer(function (req, res) {
    res.end();
}).listen(8080);

So I wonder what is the source of the problem and how to fix it.

P.S. The createServer part of the script is a trick I use so that the chrome devtools console is still running after the script has been executed. By the way, is there any more straightforward way to do it?

Update: I stumbled upon an alternative way which does not have this problem with function statement: node --inspect -e "$(< script.js)"

  • `setInterval(() => 0, 10000)` – Jonas Wilms Apr 09 '18 at 16:53
  • Thanks. By the way: `node -i -e "$(< script.js)"` works well (runs a script without a problem with function statement and opens a node repl (right in the terminal)) even without this setInterval/createServer trick. `node --inspect -e "$(< script.js)"` works well in the chrome devtools console, but still requires a setInterval/createServer trick. – Grigory Hatsevich Apr 09 '18 at 17:31

1 Answers1

1

The first script declares are local variable in the module scope, which is initialised with the function, then assigned with 1, then garbage collected - the server closure doesn't use it, see Why does Chrome debugger think closed local variable is undefined?.

The second script does not declare any variable1, it does assign to a global2. First the function, then the value 1, but global variables cannot get garbage-collected as any code that runs later might still access them.

[1]: Using var f would probably lead the the same result as with the first script.
[2]: Always "use strict" mode! You would have gotten a proper exception.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375