How to debug Node.js project in VS Code
Code debugging is an indispensable step when developing Node.js applications. VS Code provides an easy-to-use integrated debugger that can help us quickly diagnose code problems.
Preparation
Before starting debugging, make sure you have the following environments installed and properly configured:
Node.js and npm
Visual Studio Code
Installing the debugging plug-in
First, you need to install the debugging plug-in JavaScript Debugger. Select the Extensions tab in VS Code, search for and install the plugin.
Then, above the Debug bar in VS Code, click the Settings button, select "Debug Configurations", and make sure the "Node.js" environment is selected.
Select the instruction that needs to be debugged
Configure the startup file
In the left menu bar of VS Code, select the Debug tab, and then click the create a launch.json file link on the interface.
At this point, VS Code will pop up a selection box for you to choose the running environment. You need to select the Node.js environment and click "Create".
VS Code will automatically generate a default launch.json file and open it for editing. This file is used to define how to start and debug Node.js applications.
In this json file, multiple different debug templates can be configured, and each template corresponds to a different startup method.
Here is an example:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch program",
"type": "node",
"request": "launch",
"program":"${workspaceFolder}/app.js",
"console": "integratedTerminal"
}
]
}
In this template, the name attribute specifies the name of the startup template; type specifies the type of the template as Node.js; the program attribute specifies the file name and path to be started; the console attribute specifies the type of the debugging console.
After selecting the template, the data will be preprocessed in the debug bar of VS Code, and the packaging result will be generated. When startup is complete, it displays a message stating that it has successfully connected to the program being debugged.
set breakpoint
You can set breakpoints where you want by clicking on the line number section to the left of the editor. The program will stop when it reaches the breakpoint defined by the program last time, and the program will enter a pause state. Finally, the current variable values of the program can be viewed to help us find code errors.
For details about the debugging process, see the VS Code debugging tutorial.
That's all, I wish you a happy Node.js development journey!