Pro Tips To Debug Node.js Code With Examples
Developing a bug-free and defect-free application is a crucial aspect of the development process. Although perfection is almost impossible, we use Test-Driven Development (TDD) to test our code and detect errors before running it.
Debugging is the process to fix bugs during the development process. As our application grows in complexity, it becomes challenging to trace back to the source of the problem. This is where debugging techniques come in handy. Although printing statements using console.log() or console.debug() is the easiest way, it can become redundant over time.
This article provides valuable insights into the best practices for debugging Node.js applications. It includes different tools and useful methods that go beyond console.log() or console.debug(). Debugging can be done locally or remotely.
However, this article will focus on local debugging. By implementing these practices, you can easily identify and fix errors in your Nodejs web application, making it more efficient and reliable.
Let’s see how you can debug Node.js code like a pro.
Test your code
Testing is crucial for building reliable software, yet many teams overlook the benefits of test-driven development and pay the price in the long run. Skipping tests today will hurt future developers’ ability to debug code efficiently.
Tests are like documentation for code behavior and APIs, making it easier to track down bugs. For unit testing, I highly recommend the fast and feature-packed Jest library. And for API endpoints, SuperTest is an excellent choice, allowing you to pass an Express app object directly and simplifying the process of mocking dependencies.
But the real magic happens when you combine Jest and SuperTest with Husky, a Git hook utility. By using Husky’s pre-commit hook, you can run all your tests before your code leaves your machine, ensuring that your code is always reliable and bug-free. So don’t shy away from testing — embrace it and make it an integral part of your software development process!
Alternative console methods
Ah, console.log, the unsung hero of the JavaScript world! If you’re a seasoned developer, you’re probably familiar with its humble beginnings. But for those just starting out, console.log is a powerful tool that allows you to print strings and objects to the console for debugging and troubleshooting.
But wait, there’s more! Did you know that the console object has a treasure trove of hidden gems waiting to be discovered? That’s right, there are many useful methods just waiting to be utilized by savvy developers like yourself.
So, what are some of my favorite console methods, you ask? Well, buckle up and get ready to take your JavaScript game to the next level because I’m about to show you some powerful techniques that you won’t want to miss.
console.group()
It’s as simple as calling console.group() to create a new collection of logs that will be grouped together in your browser. And when you’re done with a particular group, just call console.groupEnd() to exit. Here’s an example of how you can use this feature to keep your logs well-organized and easy to read.
Output-
console.table()
Looking to organize your massive object or array with ease? Enter Console.table()! This nifty function does exactly what it promises — transforming your data into a neat ASCII table. Say goodbye to overwhelming, disorganized information and hello to structured clarity. Your brain will thank you.
Output-
console.dir()
Let me share an important point that includes two arguments, where the last one is crucial. One argument accepts an object, while the other one accepts options. By using the object option, you can adjust the console login depth.
Have you ever tried to console log a large output of a native Node.js object? It can be tough to comprehend. However, using a console.dir() with a depth property can give you a better output. So, keep this in mind for your future projects.
Output-
Debugging in Chrome using the inspect flag
My go-to method for debugging Node.js apps is simply using the inspect flag. It’s a game changer because when Node.js was first created, it seemed like we lost all the helpful debugging capabilities of the browser. But with the inspect flag, most of those capabilities come back.
All you have to do is pass the flag to your node process before starting the application, and you’re in debugging mode. Node.js creates a WebSocket connection, allowing you to remotely debug from your browser. Just make sure not to confuse the — inspect flag with the inspect command mentioned in tip three, as they launch different debuggers.
If you’re using Chrome, head over to the chrome://inspect#devices page, and you’ll see a section called remote target. There, you can view all your running node processes executed with the inspect flag. Trust me, it’s a total game-changer!
Now you need to click your created app from the list and a debugging terminal will open in Chrome for better clarity.
Debugging with POSTMAN
To effectively debug your software, it’s crucial to test it in the same way your users would. For Nodejs developers who create RESTful APIs, Postman is a handy tool that shouldn’t be missed. It lets you save and run API commands, which is particularly useful for POST requests that can’t be simulated as easily through a browser.
With Postman, you can quickly set up and send the API requests you need with just a click. So if you’re not already using it, give Postman a try and make your API development process smoother and more efficient.
Postman, a popular tool for testing APIs, has recently leveled up by adding pre- and post-scripting capabilities. These scripts empower you to tweak your requests dynamically, modifying timestamps or retaining response values for future requests.
In simpler terms, you can chain together multiple commands and use their output for subsequent requests. If you’re creating intricate RESTful APIs using Node.js, Postman is the must-have tool in your arsenal.
Debug in VSCode IDE
If you’re someone who finds it fascinating to step through your code in your browser, then get ready to be blown away because IDEs have taken it up a notch! With the inspect flag, certain IDEs allow you to do remote debugging from within your IDE, without ever having to leave it.
To make this happen, you simply need to attach an inspector to your node process and listen on the WebSocket that’s created for debugging purposes. If you’re a fan of VS Code like me, the most popular JS IDE out there, then follow along as I walk you through how to set up debugging in VS Code.
Save the below code with the file name “app.js”.
const express = require(‘express’);
const app = express();
app.get(‘/’, (req, res) => {
res.send(“World!’);
});
app.listen(3000, () => console.info(‘listening on port 3000!’));
Run the code with the following command.
node app.js
Output will be-
listening on port 3000!
Have you noticed that we’re using a different approach now?
We’re not passing the “ — inspect” flag like before, but don’t worry, there are still two ways to set up your node process with inspect mode. You can either pass the flag from within your IDE or through it. Let’s dive into the new method and explore how to set it up via your IDE.
Once your app is up and running, simply head over to VS Code and open the command palette. You can either click on the “View” tab or use the shortcut “Shift + Cmd + p”. Then, select “Attach to Node Process” and you’re good to go!
Now select the top option to attach the debugger.
Now you can access your running node process to debug. Now, open the command palette again and select the debug option.
The console displays the “debugger attached”.
Now you will see the orange bottom bar.
Hook up logging/APM tooling
Debugging your application locally is always fun with tools like inspect, but in production, that won’t be an option. So, it’s better to debug locally in the same way as you would in production.
However, logging in to the remote server to view console logs can be tedious. That’s where log aggregation tools like Stackify come in handy. They gather all your logs in one place, allowing easy parsing and visualization with powerful search and query options.
To make sense of the activity in your Node.js application, you need to monitor and observe it closely. One way to do this is by using a logging library like Winston or Bunyan, which can format and stream your logs to a centralized system.
It’s important to apply log levels, which allow you to adjust the granularity of your logs, preventing you from being inundated with unnecessary entries. Additionally, APM (Application Performance Monitoring) can help with remote debugging by extracting stack traces and analyzing them in a central location.
Ultimately, instrumenting your code with logs from the start can give you insight into your system and help you visualize your application effectively.
Test your App’s Performance
When it comes to debugging, many people assume it’s all about using the debugger to step through code. However, sometimes issues only surface under heavy load, then you must test the performance of your system.
In my opinion, Artillery is the best tool for performance testing in Node.js. With Artillery, you can create a YAML configuration file to set up the specific type of performance tests you want to run. For example, you can create a profile to see how your application handles a sudden surge of traffic after running low-traffic tests.
Give Artillery a try and you’ll be able to optimize your system’s performance and keep your users happy!
Leverage flame Graphing
Understanding how functions are executed in JavaScript is crucial for optimizing application performance. Flame graphs provide a clear visualization of the call stack, allowing you to track how functions are being called and how long they take to execute.
Unlike console.log, flame graphs like Flamebearer can show you the bigger picture of how your application is behaving and help you identify any bottlenecks in your code. So, if you want to take your JavaScript development skills to the next level, mastering flame graphs is definitely worth it.
Analyze your memory leaks
A memory leak in JavaScript is like a sneaky thief that steals your precious memory resources without giving them back. This can cause your application to become a memory hog, eventually leading to crashes and headaches.
Beware of global variables, closures, and callbacks, as they can all contribute to this pesky problem. Don’t let your leaky code drain your resources and force you to upgrade to bigger, costlier servers. Stay vigilant and keep your memory under control!
To fix memory leaks, use Chrome’s memory tab to profile the Nodejs app and find leaks.
Debugging tools
Debugging is a critical aspect of software development, as errors can completely disrupt a system’s performance. The debugging process can be challenging and is affected by various factors such as the size and structure of the system and its interactions with other systems.
Skilled developers utilize a range of approaches and tools to tackle these challenges. To aid in the debugging process, Node.js offers several popular debugging tools that developers commonly use.
- Debug by Visionmedia: A small but powerful debugging tool for Node.js, suitable for both libraries and applications and can be used in the browser too.
- Node Inspector: reliable Node.js debugger based on the Blink Developer Tools.
- Atom Node Debugger: A simple yet efficient debugging tool for Node.js and io.js that is perfect for everyday use — just open your JS file and press F5 to start debugging.
- Node Vim Debugger: This Node.js debugging client guides you through the debugging process within Vim.
- ironNode: An excellent debugger for those tired of the lengthy standard Node.js debugging process. ironNode combines JavaScript debugging power with Chrome Developer Tools.
Bug-free Efficient NodeJs Apps with OnGraph
Hey there, it’s been great hanging out with you today, but unfortunately, our time together is coming to an end. However, before we part ways, we wanted to leave you with some inspiration and helpful tips to improve your debugging skills in Node.js applications.
We hope that our insights have sparked new ideas for you and provided valuable jumping-off points to enhance your debugging process. Hiring experienced Nodejs programmers or developers can alleviate the frustration of relying solely on console.log. Discover better methods to debug your code efficiently and effectively.
So next time you’re faced with a tricky bug, remember that there are better tools and techniques available to help you out. And trust us, your sanity will thank you for it. So go forth, armed with your newfound debugging knowledge, and conquer those pesky bugs like the coding superhero that you are!
Also, read the Latest blog on NFT Platform: A Guide to Creating Your Digital Marketplace.