DEV Community

yayabobi
yayabobi

Posted on

How to use VSCode to debug a Node.js application

Debugging is an essential step in software development, as it allows developers to fix errors before releasing the software to the public. Debugging tools can be integrated into code editors, making the debugging process more efficient. This tutorial will show you how to debug node.js in Visual Studio Code.

What is Node.js?

Node.js is a JavaScript runtime environment that allows you to run JavaScript code outside a browser. It is not a framework but a technology built on Chrome's V8 JavaScript engine, allowing it to be used for developing server-side applications and command-line tools. It is also popular on the Internet of Things (IoT). Node.js has a large community of developers who have created a variety of modules that you can use in your own projects.

Node.js apps are applications written in JavaScript that are executed on a server using the Node.js runtime environment. These applications are often built on popular JavaScript frameworks and libraries such as Express, React, Angular, and Vue.

The main features of Node.js are:

  • It is an open-source server-side JavaScript runtime environment.
  • Node.js is a cross-platform runtime environment that allows you to run JavaScript code on the server-side.
  • Applications are written in JavaScript and can be run within the Node.js runtime on OS X, Microsoft Windows, and Linux.
  • Applications are single-threaded, meaning that a single process can handle multiple requests simultaneously.
  • It is asynchronous, meaning that it can handle multiple requests simultaneously without waiting for each one to finish before starting the next.
  • It uses an event-driven, non-blocking I/O model that makes it lightweight and efficient.
  • It is available under the MIT license.

While all the above is fantastic, there are bugs where there is code. Debugging becomes a common task for every developer as a side effect.

Step-by-step guide on debugging Node.js in VSCode

Prerequisites

Before we begin this tutorial, we will assume the following:

  • you have Node.js installed,
  • you have VSCode

For this tutorial, we are going to set up a simple Node.js program with an error in it.

We will then follow a debugging process that will give you the basic scope of how to use the debug tool in VSCode for Node.js.

To create our simple program, run npm init  inside an empty project directory in your console. This will give us the package.json file.

In the same directory, create an app.js file with the following code.

const calculate = (A, B) => {
  console.log('Adding...')
  let sum = 0

  sum = A + B + B + A
  return sum
 }
 ​
 const num1 = 1
 const num2 = 1
 ​
 const result = calculate(num1, num2)
 console.log(num1 + ' plus ' + num2 + ' = ' + result)
Enter fullscreen mode Exit fullscreen mode

JavaScript

Copy\
We know this is incorrect.There is a deliberate bug introduced in the sum variable. If we run the program with the command node app.js, we'd get the following output:

 Adding...
 1 plus 1 = 4.
Enter fullscreen mode Exit fullscreen mode

JavaScript

Copy

Using VSCode debug tool

VSCode comes with an inbuilt debugging tool that developers can use to debug Node.js applications. This tool is located on the left-hand side panel and looks like this:

Code Example

Alternatively, you can also use the keyword Ctrl + Shift + D to switch to the debugging panel.

Next, click on 'create and launch.json file' and select node.js.

Code Example

Code Example

You will see a configuration that looks something like this:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "pwa-node",
            "request": "launch",
            "name": "Launch Program",
            "skipFiles": [
                "<node_internals>/**"
            ],
            "program": "${workspaceFolder}\\src\\app.js"
        }
    ]
 }

Enter fullscreen mode Exit fullscreen mode

JSON

Copy

Sometimes, depending on your file directory setup or version, the assigned value to the program may not match the entry main file to your application. For that particular situation, you just need to change it to whatever your main entry file is -- which is typically something like app.js or index.js.

You can also configure the debugger to skip certain files listed under the skipFile array.

Once you've completed this, you can save and exit the file. This will change the way your debugging side panel looks. Here is the updated screenshot.

Code Example

Code Example

When you click on the play button next to run, it will launch and run the program through the debugger. The debugger console will run and exit with Process exited with code 0, which means everything worked as expected.

The process of debugging a node.js app

To debug your app.js file, you can set breakpoints by clicking on the red dot when you hover over the line number you wish to put it. A breakpoint is a place where the VSCode debugger intentionally stops or pauses the program's execution so that you can inspect state changes in the variables and watch and call stack panels located on the left-hand side of the UI.

Code Example

Code Example

Now, when you rerun the program, it will continue down the code and stop at where you placed the red dot. Looking over the variables panel will log out the current state of the values assigned. Simply right-click on the red dot and select "remove breakpoint" to remove a breakpoint.

Code example

Here, our A and B variables are set with values, but the result variable is undefined because it is yet to be defined in the program -- meaning that it doesn't exist yet.

The VARIABLE panel outputs all the current variables and their states.

Meanwhile, the WATCH panel lets you cherrypick specific variables that you want to keep an eye on. This panel is helpful because it gives you instant insight into what is happening with the code. 

If you look to the top of the UI, you will also encounter a control panel that looks something like this:

Code Example

This panel controls the debugger's progression through the program. Each control does the following:

  • Continue (F5) will run past the breakpoint and continue with the rest of the program until it hits the next breakpoint.
  • Step over (F10) will take the debugger down to the following line.
  • Step into (F11) -- this will take the debugger into the following function
  • Step out (F12) -- this will take the debugger out from the function and into the next step
  • Restart (Ctrl+shift+F5) -- restart the entire debugger
  • Stop (shift+F5) -- stop the debugging process and exit out of it

When you click on one of the above controls, you are essentially slowing down the program so you can see the updates occur in the console, the variables, watch, and call stack panels.

Going back to our code sample, it will take us to the calculate function if we click on step into. If we look at the VARIABLE panel, we see that the variables have changed to reflect the local variables. When you right-click on the variable, you can select it as a target to watch. Setting this will add the variable to the WATCH panel as per below.

Code Example

Code Example

If you click on step over, it will run the following line. Our console will simply say Adding... *because it's executed the console.log. However, the watched variable has now changed from *undefined to 0.

Code Example

If we run the following line, we will see that the sum variable inside watch has changed to the incorrect value. You can deduce that something wrong occurred in the previous line. We can now fix the issue, rerun the entire debugger, and ensure everything is working.

Code Example

Debugging code using the Lightrun tool

While debugging code during development is easy enough in VSCode -- it's a different kind of ball game when debugging in production. When there's a bug in production, we cannot simply shut down the server and take the code down to debug. Not only that, replicating production bugs in a development environment may not be possible. This is where Lightrun can help.

Lightrun is a debugging tool that enables developers to see how their code performs in real-time. It provides an intuitive interface that makes it easy to add logs, performance metrics, and snapshots to the codebase. Lightrun has several advantages over the traditional in-house debugging tools, such as offering improved visibility over the code and making it easier to identify and fix bugs.

This tool is faster and more efficient, so developers can spend less time troubleshooting the code. Using this tool also has no impact on the app's performance, which is crucial for production environments. You can book a demo today and see how Lightrun can increase your debugging process from snails' pace to lightspeed.

Lightrun for the Web is now available!

We want you to focus on what matters and be as productive as possible. Lightrun for the Web is now available, with zero integrations or configurations required. Expect all the powerful IDE capabilities and features that Lightrun offers, now running entirely on the browser and even more accessible to any of our users. 

You can connect to your live applications directly from the browser without downloading a dedicated plugin. Your experience using Lightrun for the Web matches our VS Code extension experience one-to-one, so you can count on a feature-packed, user-friendly platform that is ready to use at any time. You also have all the security controls enforced by the Lightrun Sandbox™ and many other useful extensions such as a deep GitHub integration. Plus, you can open any GitHub repo in VSCode with just a simple URL change. Ready to give it a try? Sign up here and start using Lightrun for the Web now.

Top comments (0)