Debugging is one of the most important steps when it comes to developing software. Not only does code testing ensure stability, but it also guarantees quality code and a better user experience.
Usually, developers use console.log
statements within their codebase to inspect issues. For example, look at the following JavaScript code:
console.log("This code will be printed in the console"); const i = 10; console.log("The value of i is", i);
This will produce the following output:
Even though this is a valid way to test, there is a minor issue: this is a clunky way of testing your code. There are a couple of reasons for this:
- You can’t check memory usage of the app. Tracking RAM usage is essential when it comes to optimizing performance
- No breakpoints: This means that you have no way to track the values of their variables during runtime. As a workaround, you might use
console.log
statements, but this might be a problem for large projects because you have to inspect pages of logging statements
This is where Chrome’s Developer Tools come into play. Chrome DevTools help programmers test their web apps and debug Node.js console projects with minimal effort.
Chrome DevTools supports the following features:
- Breakpoints: Lets the user track their variable values during runtime
- Memory and CPU profiling: As the name suggests, this feature helps us track the memory and CPU usage of the app
- Source maps: Maps object code to source code. This helps us read and debug compiled code in its original source
In this article, you will learn how to debug Node.js app using Chrome’s inbuilt developer tools. Here’s what we’ll learn:
Creating a project
As a first step, first initialize a black console project using the following terminal commands:
mkdir debugger-tools #create project directory cd debugger-tools npm init -y #initialize project. touch index.js #create a file called index.js
In this article, to showcase debugger functionality, we will be building a basic Express server. To make this possible, install the express
module like so:
npm install express
Using Chrome DevTools
Running the inspector
In this section, you will learn how to get started with the Chrome DevTools menu to debug your project.
First of all, navigate to index.js
. Start by writing the following code:
//file: index.js const express = require("express"); const app = express(); const port = 3000; app.get("/", async (req, res) => { //when the user is on the home directory, console.log("User is on home page"); //log out this message to the console res.send("Hello World!"); //send response to client to prevent timeout errors }); app.listen(port, () => { //run the server console.log(`Example app listening on port ${port}`); });
As a next step, we have to run the debugger:
npx nodemon --inspect index.js
This tells the compiler to attach a debugger daemon so that we can use Chrome’s DevTools to inspect our program.
Now that the daemon is running, open the debugger by following these steps:
- In an empty browser window, right click, and click Inspect to open Chrome Developer Tools
- Click the green Node.js icon. This will tell the browser to launch the Node.js debugger
Here are the steps in GIF form:
Let’s now test our code! Go to localhost:3000
:
As you can see, every time the user refreshes the page, we get console logs in the DevTools’ Console view. This indicates that Node.js has successfully attached a debugger to our program.
Inserting breakpoints in Node.js
The breakpoints feature is arguably the most important feature in the debugger toolset. As the name suggests, they pause code execution whenever it reaches a certain point. This can be useful in the following situations:
- When tracking the values of variables during code execution
- Inspecting the call stack. This is crucial in situations where you want to check whether the project is actually calling critical functions during the app’s lifecycle
The following code will help us understand debuggers:
let count = 0; //initialize a count variable. app.get("/", async (req, res) => { console.log("User is on home page"); count++; //when the user visits this page, increment the count variable console.log("User visit count", count); //log out its value res.send("Hello World!"); });
To enable breakpoints, perform the following steps in the DevTools window:
- Select Sources
- Double-click the line where you want the breakpoint; in our case, it is
line 9
. This tells the debugger that we want the breakpoint to track the value of thecount
variable
When we run the code, we can see that the debugger pauses code execution every time it reaches line 9
.
Thanks to the debugger service, we can now track the value of count
during the program’s runtime.
Using the Debugger
keyword
Other than enabling breakpoints through DevTools, we can even use the debugger
keyword in our code. This is great for situations where we don’t want to manually activate breakpoints through the GUI.
This piece of code demonstrates how to use the debugger
keyword:
const count = 0; const myArray = []; //create an empty array app.get("/", async (req, res) => { console.log("User is on home page"); count++; myArray.push(count); //push element into this array debugger; //activate a breakpoint. //All of the variables before this line will be tracked console.log("User visit count", count); res.send("Hello World!"); });
This will be the output of the program:
Using the memory profiler
Memory profilers help developers track their app’s memory usage. This is useful when programmers want to track down memory leaks. As a result, this helps with optimizing the project’s performance.
To use a memory profiler, follow these steps:
- Go to Memory
- Then, make sure Heap Snapshot is selected
- Afterwards, scroll down and click Record
In this option, you can see how much memory your program consumes in total.
Furthermore, if we expand each option, we can get a deeper insight into how much memory our code is using. Consequently, this lets us monitor the project for memory leaks.
Conclusion
As stated before, Google’s Chrome DevTools is one of the most crucial pieces of software used during app development. Not only does it help programmers squash bugs, but it also helps them enhance their app’s user experience. Ultimately, this leads to more happy users and clients.
Thank you so much for reading!
200’s only
Monitor failed and slow network requests in production
Deploying a Node-based web app or website is the easy part. Making sure your Node instance continues to serve resources to your app is where things get tougher. If you’re interested in ensuring requests to the backend or third party services are successful, try LogRocket. 
LogRocket is like a DVR for web and mobile apps, recording literally everything that happens while a user interacts with your app. Instead of guessing why problems happen, you can aggregate and report on problematic network requests to quickly understand the root cause.
LogRocket instruments your app to record baseline performance timings such as page load time, time to first byte, slow network requests, and also logs Redux, NgRx, and Vuex actions/state. Start monitoring for free.