1

Having a file (let's call it script.js) with the following content:

console.log("Hello World!");

(so, one line with a console.log on it)

Runnning node script.js it outputs "Hello World!".

The problem is when I run node debug script.js. I get the following output:

$ node debug script.js 
< debugger listening on port 5858
connecting... ok
break in script.js:1
  1 console.log("Hello World!");
  2 
  3 });
debug> 

Why did the last 2 lines appear?

It looks for me like a bug but maybe there is another explication?

3
  • 1
    I understand Node automatically wraps your code in a function (i.e. the module pattern) and that would explain the last "});" but I am surprised you don't see a new first line with "function(exports) {" too. Commented Jan 22, 2014 at 14:42
  • @HectorCorrea It's only showing a couple of lines after the line that it hit the breakpoint on. Commented Feb 10, 2014 at 17:02
  • github.com/nodejs/node/issues/9768 Commented Sep 22, 2017 at 8:48

1 Answer 1

3

It's just showing a portion of the code you were debugging before the process ended. The code you write in node gets dropped into a function which provides it all the variables it needs in that scope. This is how they get around the whole global scope variable problem because every module has its own "global" scope.

A good example of this can be seen while debugging with node-inspector. It lets you click through the assets of your project while debugging.

I created a script.js file with console.log("Hello, world!"); as the only line. Check out what it looks like inside node inspector:


To install node-inspector:

  1. npm install -g node-inspector

  2. Open a terminal, type "node-inspector", and the app will start running.

  3. Navigate to http://localhost:8080/debug?port=58581. You'll see a screen like this:

  4. Now run your application node --debug-brk script.js in another terminal window. --debug-brk just causes node to break on the first line of your application until a debugger is attached.

  5. Refresh the node-inspector page and then you can start debugging :D

Sign up to request clarification or add additional context in comments.

4 Comments

Where do you see this?
This is node-inspector. See my edit for how to install and use it :)
A gif screen record! ;-) Nice. Thank you!
No problem. They're my new favorite way to show something quickly :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.