Debugging is an integral component of software development. It serves to understand its tactics and intricacies and lay a firm foundation for any development process initiatives.

When building Node.js applications, various debugging techniques may be utilized when providing Node.js development services. This article will discuss these methods and how to utilize a terminal, the Node.js debugger statement, Chrome Dev Tools, and Visual Studio Code to debug Node.js applications.

node.js debugging: pro tips for efficient troubleshooting

Boost Your Business Revenue with Our Services!

How To Debuggle Node.Js Like A Pro With These Tricks And Strategies

How To Debuggle Node.Js Like A Pro With These Tricks And Strategies

As our starting point, let us build a simple application with this scenario in mind: Our job will be to develop an app that retrieves data from its source (using JSON placeholders to do this) and modifies it before sending it back out to be processed by Node.js.

Before saving our information to our application folder's JSON file, let's create our application as decoupled as possible. Here are some tips to answer how to debug NodeJS

Construction Of Application

To generate a package.json file, first, we will create a folder named NodeJS-debugging and run npm init -y. Then, using npm i express axis cors nodemon, we can install the ExpressJS framework, Axios fetch data correctly, and Cors ensures no cors errors.

Nodemon monitors server changes when modifications are made to the NodeJS application server.

Assuming we're using Linux, the following commands should help create index.js and its related folders: touch index.js and mkdir controllers data routes.

Before beginning to code, we should edit our package.json file according to these powerful tools directions: These scripts include start and dev commands to initiate Nodemon for development mode purposes and the node process, respectively. As development progresses, we intend to write our express server code in an index.js file.

As you can see, we've added several extra lines - for routes, posts, and values. We still need to set up all of these routes on our server, so running npm run dev won't work.

We aim to modularize as much code as possible so we no longer find code snippets ourselves staring into an index.js file whenever something needs to be discovered or understood. Instead, we encounter a managed folder structure when figuring something out!

Composing The Controllers

Now, let's create our controllers.js file within our controllers directory and add this snippet: Let's investigate what this code is accomplishing.

Step two is identifying a real-time application and creating the posts.json file (data folder). To avoid errors caused by its absence, we generate random numbers between 1 and 10 for every item we own, appending their rating key/value pairs using spread.

Finally, when all is complete, we utilize catch statements to manage errors that arise from their absence in the runtime environment. So that the getPosts function can be utilized by our routes, we exported it.

Assuming everything goes according to plan, we should have an array of 15 posts called data/posts.json with 15 elements similar to this image: Here, the rating field contains an arbitrary random number.

In contrast, the userId, ID, Title, and Body fields come directly from API. Now that our controllers have been written, it is time to write their routes so we can call them using curl or Postman and import them in index.js.

Using Visual Studio Code For Debugging

Now is the time to use Visual Studio Code directly for debugging code. First, we should launch and close down our inspection server before opening visual studio debug NodeJS itself; upon clicking Run and Debug, we should see an area with similar options on the left that prompt us with similar screens identical to this:

The Inspection Server will start when we click Launch in the upper-left corner or press F5. Sending Postman requests with "Get request: controllers.js debugger as app development keywords " will take us directly there.

Like Chrome Dev Tools, a new rating would appear every time the page was refreshed. We can again review ratings to identify issues by utilizing this tool and methodology. Once this has occurred, further investigation of their cause must ensue.

Assembling Itineraries

WordPress Create a posts.js file within your routes directory and paste this code inside its contents: Here we create a base route for the getPosts function from the controllers.js file by importing Express and utilizing its router; additionally, export this router.

Now we can interpret our index.js file correctly: A request made at https://localhost:5000/posts will create the data/posts.json file precisely as indicated.

Once our working project is complete, we can explore NodeJs debugging features, such as using Watchers and Terminal for Debugging.

Simply run node inspect index.js by development team [or other file] from within NodeJs to begin this exploration; when we do so, the Terminal should display this message:

Now, we enter the realm of debugging. To take actions using specific keywords. Press C or continue, and the code will continue running up to its next breakpoint or end if you press C; press N for next; to move directly onto another line, press N and go directly there.

Step into any function by pressing s or step, while exiting features with press o will do. To pause running code, write pause.

Ultimately, this Terminal would show what would happen if we hit "n" several times to watch out the value constant full stack development before hitting it back again to resume the execution of our code.

As shown by the JS debugger, this operation yielded two. As we specified, we desired to monitor its value constant.

Similar to adding console.log statements but more useful for specific scenarios (i.e., entering queues when pushing buttons hundreds of times is required to enter it), this method allows us to monitor constant values such as they would occur under console logging statements. Since such lines of code measures as source code would likely prove ineffective, we provide another alternative solution for that scenario.

Use Of Debugger Keyword For Debugging

For debugging purposes, the debugger keyword needs to be included after each value constant in the index.js file - in this instance: Now, when rerunning node as testing tool code execution inspects index.js, when we press C, our debugger can jump straight to where the debugger keyword has been declared without having to press N multiple times; as a result, we are free to add viewers as needed; below is an illustration of this workflow process:

Chrome DevTools Debugger For Node.JS

We will now employ some different debugging tools to track down one of our controllers that's malfunctioning.

Let's assume one controller has become dysfunctional. Const rating = crypto.random (1, 11); should have been written instead since typing 11 will cause negative ratings - something we want to avoid! Unfortunately, after sending our get request and running our application, we discovered some ratings are negative!

Even though this example may seem straightforward, suppose we were working with an expansive function that calls other functions that, in turn, still call other functions in the online community.

We needed to determine where our issue lay exactly. Chrome Dev Tools allow us to monitor the state of applications running in browsers based on Chrome or Chromium more efficiently and visually.

Let's stop our server and modify its postData function with this code:

Relaunch debug NodeJS application using a slightly altered command: node -inspect index.js.

Now that the lines have been included before inspection, our browser can connect directly to our server: navigate, and you should see precisely what should be visible: By selecting "Open dedicated DevTools for Node" in this section, the following will open:

As is evident here, this place is alive with activity. On the left side, we can inspect code and modify directories/files as desired, while watchers use in the debugging process - keywords that the debugger searches for - are defined on the right; to access ratings, we enter "rating." Without adding a debugger keyword to controllers.js, we wouldn't be able to observe rating values at a glance.

When we launch Postman and send new get requests to /posts, this screen should appear:

Now we see that our rating has a value of -9 and can easily conclude that our code has an error; our constant takes between -11 and 11.

If we were to press F8 again to continue execution, however, the value would change to show something completely different: Since our application ends at Postman, if we check his activity log, we should see that the execution of our application continues apace.

Get a Free Estimation or Talk to Our Business Manager!

Summary

In conclusion, this blog discussed various debugging techniques for NodeJS applications, emphasizing their value over just using console.log commands alone.

If possible, outsourcing NodeJS development services to make development processes more efficient; that way, you could take advantage of professional knowledge and expertise while improving overall project quality and efficacy.

Paul
Full Stack Developer

Paul is a highly skilled Full Stack Developer with a solid educational background that includes a Bachelor's degree in Computer Science and a Master's degree in Software Engineering, as well as a decade of hands-on experience. Certifications such as AWS Certified Solutions Architect, and Agile Scrum Master bolster his knowledge. Paul's excellent contributions to the software development industry have garnered him a slew of prizes and accolades, cementing his status as a top-tier professional. Aside from coding, he finds relief in her interests, which include hiking through beautiful landscapes, finding creative outlets through painting, and giving back to the community by participating in local tech education programmer.

Related articles