Search code examples
javascriptbreakpoints

Insert break point into a javascript file


I would like to insert break point at a position listed in the below quote. Let's say the below quote belongs to a js file called "test.js". What I would like to do is when I run "node test.js" on the command line, it will break at the break point and then I can inspect all the variables available at the break point.

var a = 4;

function changeA(input) {
  var input = 6
  [INSERT BREAK POINT HERE]
  console.log(input)
};

changeA(a);
console.log(a);

Or is there another way to insert break point to a javascript file?


Solution

  • You can hardcode a breakpoint like this:

    debugger;
    

    E.g.:

    function changeA(input) {
      var input = 6
      debugger;
      console.log(input)
    }
    

    ...but you have to be using a debugger for it to mean anything, such as node-inspector. And if you're using a debugger, you can set breakpoints through the debugger itself (rather than hardcoding them).

    Here's an example of debugging a very simple NodeJS script via node-inspector:

    Script:

    var a = +process.argv[2];
    var b = +process.argv[3];
    var c = a + b;
    console.log("c = " + c);
    

    Command to start node-inspector and pass my script a couple of args:

    node-debug temp.js 10 20
    

    A browser pops up with a debugging UI and the program paused. I've set a breakpoint through the UI on the var b = ... line, and then stepped passed it once, so I'm sitting on the var c = a + b; line (which hasn't run yet):

    enter image description here