Debugging is the task to identify and remove errors from software applications, and is more than just printing out values in your code. This post describes how to efficiently debug Node.js programs using the latest Google Chrome DevTools.
Why console.log is not the best option?
Using console.log to debug your code generally dives you into an infinite loop of “stopping your app, adding a console.log, and start your app again” operations. Besides slowing down the development of your app, it also makes your writing dirty and creates unnecessary code. Finally, trying to log out variables alongside with the noise of other potential logging operations, may make debugging difficult when attempting to find the values you are debugging.
Debugging tools provide you with a few important functionalities that console.log isn’t able to provide. In particular they let you pause the execution of your application at specific points in the code, and inspect and modify the values of the variables while the program is still running.
Setting up Chrome for Node.js debugging
With Chrome 57+, the Node.js debugging feature is enabled as default and there is no need to manually enable it from the Experimental Feature panel anymore like in the older versions.
If you haven’t done it yet, update Google Chrome to the latest version and be sure you are using Node.js 6.4+.
To start debugging, run your Node.js application with the --inspect flag.
$ node --inspect <your_file>.js
Next, ignore the URL starting with “chrome-devtools://” that is displayed in your terminal, but open “about:inspect” in Google Chrome instead.
Finally, click on “Open dedicated DevTools for Node” to start debugging your application’s code.
Moreover, the official documentation on debugging Node.js App offers a detailed list all the other inspector tool and client alternatives.
Chrome DevTools in action
To conclude this article, I want to give an overview of the Chrome DevTools in action for the following Express application.
Let’s run it with the --inspect flag and open the dedicated DevTools for Node as explained before.
In particular, as you can see in the images below, you can insert breakpoints to stop the execution of your program, inspect and “hot-swapping” the values of the variables.
If you have any questions on this or updates, please reach out to me on Twitter at @JacopoDaeli.