Best Practices for Debugging in Node.js

Best Practices for Debugging in Node.js

An important part of development is the ability to make the application bug-free and defect-free. It is almost impossible to write a perfect application, but we follow TDD (test-driven development), which helps us test our code before running. If something fails, we can then easily trace the error and resolve it.

The art of fixing bugs/defects is called debugging. With time our application grows and can become complex. In such cases, it can be difficult to trace back to that single line of code that is creating a problem. To solve this issue, we can use different debugging techniques. One of the common practices among developers is to print statements as the program runs, i.e., console.log() or console.debug(). While this is the easiest method, it is also redundant. We have to add an extra statement every time we need to check some data.

This article compiles some of the best practices to debug the Node.js application. Here, we will get familiar with different tools and other useful methods apart from console.log() or console.debug()*.*

Debugging can be done in two ways — locally on the machine where the software is or remotely. In remote debugging, you debug an application running in an environment different from your local machine. However, we will not be focusing on remote debugging in this article.

Prerequisites

  • Node.js should be installed in your local environment. Type node -v in your terminal. If the node is installed, you will see the node version, i.e., ​​v16.13.0. If not, check out Node.js’s official website.

  • You should have a basic understanding of JavaScript.

  • You should be familiar with Chrome DevTools.

Let’s check out the different ways we can debug node applications.

  • Debugging using the built-in Node.js debugger

  • Debugging using console

  • Debugging with Chrome using Chrome DevTools.

Built-in Node.js debugger

The debugger gives us a way to look inside the program without exposing it to any security threats.

var fs = require(‘fs’);fs.readFile(‘test.txt’,
‘utf8’, function (err, data
) {debugger;if (err) throw err;});

We have used a debugger that lets us watch objects and add breakpoints. So, we can track code line by line.

  • Create a file, test1.js (you can name your file whatever you want), and run node inspect test1.js.

The terminal should look like this: Debugger listening on…

Let’s have a look at the list of commands we can use during debugging:

cont or c: Continue executionnext or n: Step nextstep or s: Step inout or o: Step outpause: Pauses the codewatch: Add the expression or variable to watch.watcher: List the watchers with their values.

We have added data to watch. As you can see, we are getting the content: ‘Hello this is first text file’.

Debugging using Console

We all are aware of console.log. It is commonly and, I would say, excessively used. But other useful methods come in handy while debugging. Some of the methods to better display object properties are :

  • console.dir() displays the properties of the specified object in the console in an interactive list, making it easier to view for developers.

  • console.group() creates a new collection of console logs by nesting all the logs together like this.

  • console.groupEnd() is used to exit the current group.

Some other useful methods are:

warn() — display warning messagetable(obj) — display arrays of objects in tabular formaterror(msg) — display an error messagecount(label) — displays the number of times the line has been executedtime(label) — to calculate the duration of an operationclear() — clears the consoletimeEnd(label) — stops the timer to give the total duration

Source

Debugging Node.js with Chrome DevTools

Node.js also uses the V8 JavaScript engine. So, the popular choice among Node developers in Chrome DevTools.

Let’s start by creating a Node application that will run an HTTP server and return a JSON response. The application will return a JSON with a city name. We will have an array of cities. We will run this application on port 8000. You can define your port number.

Let’s import the HTTP module, which is needed to create an HTTP server. The getCityName() function randomly selects a city name and returns it.

Next, we will add the request listener, requestListener(), that processes HTTP requests.

Add the below code in app.js. The code editor used here is VS code. You can choose any editor you are comfortable with. Also, I am using a built-in terminal provided by VS code.

const http = require(“http”);const host = ‘localhost’;const port = 8000;const cities = [“Mumbai”, “London”, “New York”, “Rome”, “Tokyo”];const getCityName = function () {let city = cities[Math.floor(Math.random() * cities.length)];return city}const requestListener = function (req, res) {let message = getCityName();res.setHeader(“Content-Type”, “application/json”);res.writeHead(200);res.end(`{“message”: “${message}”}`);};const server = http.createServer(requestListener);server.listen(port, host, () => {console.log(`Server is running on http://${host}:${post}`);});

Go to the terminal and type node — inspect app.js.

Remember: While using CLI, you use inspect instead of — inspect*.*

After running the above command, you should get something like this in your terminal.

Now, navigate to Google Chrome and type chrome://inspect

The above screen should appear. Click on inspect under Remote Target. We will be able to debug node code with Chrome. Navigate to the Sources tab on the left-hand side. If your left-hand side is empty, import the workspace where you have written your code and select app.js.

Let’s start debugging by adding breakpoints. Click number 10 in the debug console. A red dot will appear next to the number and the right-hand panel, indicating a new breakpoint has been added.

Next, add a watch expression. On the right side, click the arrow next to the Watch header, then

click +. Enter the city and press ENTER to observe its value when processing a request.

Next, open a new browser window and navigate to http://localhost:8000.

This is the screen of the inspect screen where you can easily debug your application.

Conclusion

In this article, we learned the different ways we can debug a node application and some best practices that can help us become better developers. We created a node application and debugged it using a debugger, breakpoints, DevTools, and watchers.

One of the skills that a developer must know is how to debug better. I hope the practices mentioned in this article will help you to become a better developer.

You can also refer to Node.JS’s official documentation to learn more about node debugging.