Debugging a Node.js application is very similar to debugging any other application. IDEs like WebStorm or IntelliJ provide a traditional debugger where you can install breakpoints and stop the execution whenever the application hits the given line.
This is perfect if you buy a license for one of the IDEs, but there is a free alternative that will have a very similiar result for the users of Google Chrome, node-inspector.
Node-inspector is an npm package that pretty much enables the Chrome debugger to debug Node.js applications.
Let's see how it works:
npm install –g node-inspector
This should add a command to our system called node-inspector
. If we execute it, we get the following output:
That means our debug server has started.
Let's take a simple Seneca act as an example:
var seneca = require( 'seneca' )() seneca.add({role: 'math', cmd: 'sum'}, function (msg, respond) { var sum = msg.left + msg.right respond(null, {answer: sum}) }) seneca.add({role: 'math', cmd: 'product'}, function (msg, respond) { var product = msg.left * msg.right respond( null, { answer: product } ) }) seneca.act({role: 'math', cmd: 'sum', left: 1, right: 2}, console.log) seneca.act({role: 'math', cmd: 'product', left: 3, right: 4}, console.log)
node index.js --debug-brk
The way to access the debugger is through the URL http://127.0.0.1:8080/?port=5858
:
I am sure this image is very familiar to every developer in the world: it is the Chrome debugger showing our code. As you can see in the first line, the one highlighted in blue, the application stopped in the first instruction so that we can place the breakpoints by clicking the line numbers, as shown in the following image:
As you can see in the preceding image, we have installed a breakpoint in line 9. Now we can use the control panel to navigate through the code and values of our variables:
The controls on the top speak for themselves if you ever debugged an application:
If we click on play, we can see how the script will stop in line 9 in the following image:
As a good debugger, it will let us inspect the value of our variables by hovering the cursor over the variable name.