Debugging helps you find and fix mistakes in your code. VS Code makes this easy by letting you pause and check your program step-by-step.
Debugging with VS Code in Node.js
1. Open your Node.js project in VS Code. 2. Go to the Run and Debug view (left sidebar or press Ctrl+Shift+D). 3. Click 'create a launch.json file' to set up debugging. 4. Choose 'Node.js' environment. 5. Add breakpoints by clicking next to the line numbers. 6. Press the green play button to start debugging. 7. Use controls to step over, step into, or continue running.
The launch.json file tells VS Code how to run your program for debugging.
Breakpoints pause your program so you can check what is happening at that moment.
app.js in your project folder when debugging.// launch.json example
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js"
}
]
}// Setting a breakpoint
// Click on the left side of the line number in your code editor to add a red dot.
// When you run the debugger, the program will pause here.This simple Node.js program adds two numbers. You can set a breakpoint on the line where result is calculated to see the values of a and b during debugging.
console.log('Start program'); function add(a, b) { const result = a + b; // Set breakpoint here return result; } const sum = add(5, 7); console.log('Sum is:', sum);
You can watch variables and call stack in the Debug panel to understand your program better.
Use the Debug Console to run commands or check variable values while paused.
Remember to remove or disable breakpoints when you finish debugging to avoid pausing unnecessarily.
Debugging with VS Code helps you find errors by running your code step-by-step.
Set breakpoints to pause your program and inspect variables.
Use the launch.json file to configure how your Node.js program runs in the debugger.