How To Debug A Node.js App In Visual Studio Code

Node.js

22/04/2021


Debugging a Node.js app inside Visual Studio Code is quite straightforward.

Add a new script

In your package.json file, add a new npm script called "debug".

JSON
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js",
"debug": "node --inspect app.js"
},

debug is essentially a copy of start with --inspect added before the main application file. What this does is attach your debugger to the Node.js application.

Start the debugger

To launch your debugger, open the integrated terminal and create a new "JavaScript Debug Terminal".

Selecting a new terminal type

Source from Visual Studio Code

Then run your debug command (e.g. npm run debug) and you're in!

Debug with configuration

You may skip the rest of this post if your debugging requires no configuration.

There are situations where you might want to configure your debugger (e.g. Nodemon). Create a new file called .vscode/launch.json at the root of your project. It should have the following content:

JSON
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "attach",
"name": "Node.js",
"processId": "${command:PickProcess}",
"protocol": "inspector",
},
]
}

Let's briefly go over the configurations properties one by one:

  • type: Debug in Node.js
  • request: Set up an 'Attach' configuration
  • name: Name of the configuration
  • processId: Use the selected process ID for debugging
  • protocol: Use the inspector debug protocol

Start the configured debugger

Instead of running your debug script in a special debug terminal, run it in a regular one this time. Next, head over to the debugger tab, select your configuration from the dropdown and click on the arrow button.

Starting debugger from debugger tab

You will the be prompted to select the process you wish to debug. If you don't know the process ID of your Node.js program, check the terminal where you ran the debugger script.

Debugging Nodemon

If you're running your Node.js application with Nodemon, you should add the restart property to your configuration file:

JSON
"configurations": [
{
// ...
"restart": "true",
},
]

This tells the debugger to reattach whenever your Node.js process restarts.


WRITTEN BY

Code and stuff