When first learning Node.js, I would employ "console.log" as a panacea whenever I needed to debug an issue, which was obviously not very efficient. I recently discovered Node Inspector, an amazing and much more efficient debugging tool for Node.js. In this blog post I walk through how to get going with Node Inspector in a sample application.
Start by creating a simple Node/Express application using our humble terminal.
Follow the terminal prompts, and then you should be good to go. If you need to, restart the server. I personally use nodemon to automatically restart my server, so that I do not have to manually restart the server every time a change has been made to the application code.
~/test_app$ nodemon 28 Nov 12:52:45 - [nodemon] v1.2.1 28 Nov 12:52:45 - [nodemon] to restart at any time, enter `rs` 28 Nov 12:52:45 - [nodemon] watching: *.* 28 Nov 12:52:45 - [nodemon] starting `node ./bin/www`
Start the application by visiting localhost:3000.
Next install Node Inspector by running "npm install -g node-inspector" (you may need to enter admin credentials to continue).
~/test_app$ npm install -g node-inspector
Now run the inspector.
~/test_app$node-inspectpr test_app$ node-inspector Node Inspector v0.7.4 Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.
Visit the link from the terminal prompt to start debugging. You should see something similar to this:
In order to have your code run inside the Node Inspector console, you need to change the way nodemon is run by appending "--debug" to it, as shown below:
You should see the application code inside the Node Inspector console after refreshing the page.
We are now ready to test our awesome debugger. Head to the routes/index.js of your application and put in place a break point:
Refresh your index page (the one that runs on localhost:3000). You will notice that the page will continuously load because of the break point. Return to the Node Inspector console; now you will be able to debug the application.
If you want to debug the entire app by running through each line of code, you will need to set a break point before Express runs, as shown below:
If you refresh the page the application will not pause due to the newly added break point. In order to overcome this you will need to restart the server, even if you are using nodemon. Append the command with "-brk", and then restart the sever:
~/test_app$ nodemon --debug-brk
Now everything should work just fine.