0
0
Node.jsframework~5 mins

Debugging with VS Code in Node.js

Choose your learning style9 modes available
Introduction

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.

When your Node.js program crashes or shows errors.
When you want to understand how your code runs line by line.
When you need to check the values of variables during execution.
When you want to test different parts of your code without guessing.
When you want to improve your code by finding hidden bugs.
Syntax
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.

Examples
This setup tells VS Code to run app.js in your project folder when debugging.
Node.js
// launch.json example
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch Program",
      "program": "${workspaceFolder}/app.js"
    }
  ]
}
Breakpoints let you stop the program exactly where you want to check variables or flow.
Node.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.
Sample Program

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.

Node.js
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);
OutputSuccess
Important Notes

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.

Summary

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.