0
0
NodejsHow-ToBeginner · 3 min read

How to Use Node Inspect in Node.js for Debugging

Use node inspect <filename.js> to start the Node.js debugger in your terminal. It lets you pause execution, step through code, and inspect variables interactively.
📐

Syntax

The basic syntax to start debugging with Node.js is:

  • node inspect <filename.js>: Launches the debugger for the specified file.
  • cont: Continues execution until the next breakpoint.
  • next: Steps to the next line in the current function.
  • step: Steps into a function call.
  • out: Steps out of the current function.
  • repl: Opens a prompt to evaluate expressions.

This lets you control program flow and check values while running your code.

bash
node inspect filename.js
💻

Example

This example shows how to debug a simple script that adds two numbers. You can pause execution, check variables, and step through the code.

javascript
/* save as add.js */
function add(a, b) {
  const sum = a + b;
  return sum;
}

const result = add(5, 7);
console.log('Result:', result);
Output
Result: 12
⚠️

Common Pitfalls

Common mistakes when using node inspect include:

  • Not placing debugger; statements or breakpoints, so the debugger runs without stopping.
  • Confusing next and step commands; next skips over functions, step goes inside them.
  • Forgetting to use cont to resume after a breakpoint.
  • Trying to debug asynchronous code without understanding how callbacks and promises pause execution.

Always add debugger; in your code where you want to pause or use the debugger commands to set breakpoints.

javascript
/* Wrong: No debugger statement, no breakpoints */
function multiply(a, b) {
  return a * b;
}

console.log(multiply(3, 4));

/* Right: Add debugger to pause */
function multiply(a, b) {
  debugger;
  return a * b;
}

console.log(multiply(3, 4));
Output
12
📊

Quick Reference

CommandDescription
contContinue execution until next breakpoint
nextStep to next line in current function
stepStep into function call
outStep out of current function
pausePause execution
replOpen interactive prompt to evaluate expressions
watch(expr)Watch expression value
unwatch(expr)Stop watching expression

Key Takeaways

Start debugging with 'node inspect filename.js' to run the built-in Node.js debugger.
Use commands like 'cont', 'next', 'step', and 'out' to control code execution flow.
Add 'debugger;' statements in your code to set breakpoints easily.
Remember to resume execution with 'cont' after hitting a breakpoint.
Use the 'repl' command to inspect variables and test expressions during debugging.