Interactively Debugging Node.js Applications

The power of interactive debugging is under appreciated until you’ve had the pleasure of using a development tool that supports it. Personally, I was first introduced to such a tool when I was working with Microsoft’s Visual Basic 5 but later got re-introduced and learned the power of debugging Java in Eclipse. Today, Visual Studio and Eclipse are still leaders in this space.

As web technologies have been on the rise, especially JavaScript, CSS, and HTML, there developed a need for interactive debugging in the browser, hence, Firebug was born which later became the catalyst for Chrome DevTools and Firefox Developer Tools. Web developers now had a really nice interface for introspecting their live running code, styles, and layout. Additionally, line-by-line debugging of JavaScript became easier than ever before with breakpoints, single-stepping, variable introspection, and live code evaluation.

Newer server-side technologies like Node.js didn’t immediately have all the power of interactively debugging the way Java and other languages do. Developers are lazy and thus revert to using console.log statements to debug — a very painful and highly inefficient method. Thankfully, an open source project called node-inspector provides an excellent solution that gives you the same interface you’re familiar with in Chrome DevTools to debug your running Node.js applications. It is very simple to setup and start using.

Get started easily

Note: node-inspector only works with Chrome or Opera (presumably any WebKit powered browser).

From the command-line:

npm install -g node-inspector

Start your app with node-debug (instead of node or nodemon):

node-debug app.js

If everything works correctly, you should see output similar to the following:

debugger listening on port 5858
Node Inspector is now available from http://localhost:8080/debug?port=5858
Debugging `app.js`

Additionally, your default browser should have opened to the URL in the output. You now have a powerful interactive debugger attached to your running Node.js code. I recently used this myself when I was trying to sort out a complex issue in a custom proxy I wrote at work. I was able to set a breakpoint in my code and then step through it line-by-line, inspecting variables, testing conditionals, etc. It saved me hours of trying to figure out the issue with archaic means such as console.log statements.

In a future post, I will demo a simple, visual walk through of how to use node-inspector to step through your code. In the meantime, simply place the keyword debugger anywhere in your code to place a breakpoint and activate the debugger for line-by-line debugging.

You can read more of the documentation of node-inspector on GitHub.


Originally published at khayes.co.

Show your support

Clapping shows how much you appreciated Kyle Hayes’s story.