Grigory Hatsevich
Grigory Hatsevich

Reputation: 419

function statement's strange behavior when inspecting node.js in chrome devtools

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)"

Upvotes: 0

Views: 62

Answers (1)

Bergi
Bergi

Reputation: 665361

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.

Upvotes: 1

Related Questions