TExcelTAD
Home › Node.js › Node.js Debugging

Node.js Debugging

Every program has bugs. Debugging is the skill of finding out what your program actually does, as opposed to what you think it does. Node gives you three levels of tools: smarter console output, readable stack traces, and a full interactive debugger that works with Chrome DevTools and VS Code.

Level 1: better console output

console.log is still the fastest way to peek at a value, but Node's console has more to offer:

node · try it yourself
const order = {
  id: 42,
  customer: { name: 'Mai', address: { city: 'Hanoi', geo: { lat: 21.03, lng: 105.85 } } },
  items: [{ sku: 'A1', qty: 2 }, { sku: 'B7', qty: 1 }],
};

console.log(order);                        // nested objects deeper than 2 levels are cut off
console.dir(order, { depth: null });       // show everything
console.log('%s ordered %d items', order.customer.name, order.items.length);
console.table(order.items);

console.group('checkout');
console.log('validating…');
console.log('charging card…');
console.groupEnd();

console.count('retry');
console.count('retry');
{
  id: 42,
  customer: { name: 'Mai', address: { city: 'Hanoi', geo: [Object] } },
  items: [ { sku: 'A1', qty: 2 }, { sku: 'B7', qty: 1 } ]
}
{
  id: 42,
  customer: {
    name: 'Mai',
    address: { city: 'Hanoi', geo: { lat: 21.03, lng: 105.85 } }
  },
  items: [ { sku: 'A1', qty: 2 }, { sku: 'B7', qty: 1 } ]
}
Mai ordered 2 items
┌─────────┬──────┬─────┐
│ (index) │ sku  │ qty │
├─────────┼──────┼─────┤
│ 0       │ 'A1' │ 2   │
│ 1       │ 'B7' │ 1   │
└─────────┴──────┴─────┘
checkout
  validating…
  charging card…
retry: 1
retry: 2
Method Use it for
console.dir(obj, { depth: null }) fully expanded nested objects
console.table(array) arrays of objects as a table
console.error(...) messages to stderr (kept apart from normal output)
console.time('x') / console.timeEnd('x') measuring how long something takes
console.trace('here') print a stack trace showing how you got here
console.assert(cond, msg) print msg only when cond is false

Level 2: reading stack traces

When an error is not caught, Node prints its stack trace: the chain of function calls that led to it, newest first. The first line that points into your code is usually where to look. An error object exposes the same information in err.stack:

node · try it yourself
function parsePrice(text) {
  const value = Number(text);
  if (Number.isNaN(value)) throw new TypeError(`Not a price: "${text}"`);
  return value;
}

function totalOf(lines) {
  let sum = 0;
  for (const line of lines) sum += parsePrice(line.split(';')[1]);
  return sum;
}

try {
  totalOf(['pen;1.5', 'book;12', 'lamp;n/a']);
} catch (err) {
  console.log(err.message);
  const frames = err.stack.split('\n').slice(1, 3)
    .map((l) => l.trim().split(' (')[0]);    // keep the function names, drop file paths
  console.log(frames);
}
Not a price: "n/a"
[ 'at parsePrice', 'at totalOf' ]

Reading from the top: the error was thrown in parsePrice, which was called from totalOf. A real trace also shows file:line:column for each frame.

Tip: Add context to errors you re-throw with the cause option: throw new Error('Could not load invoice', { cause: err }). Node prints both errors, so you don't lose the original trace.

Level 3: the inspector

For hard bugs you want to pause the program and look around. Start Node with the inspector enabled:

bash · try it yourself
$ node --inspect-brk app.js
Debugger listening on ws://127.0.0.1:9229/3f2b1c9e-0a7d-4e55-9a1e-6b2f0c8d7e41
For help, see: https://nodejs.org/en/docs/inspector
Debugger listening on ws://127.0.0.1:9229/3f2b1c9e-0a7d-4e55-9a1e-6b2f0c8d7e41
For help, see: https://nodejs.org/en/docs/inspector
Flag Meaning
--inspect enable the debugger, keep running
--inspect-brk enable it and pause on the first line
--inspect=0.0.0.0:9230 choose host and port (careful: never expose it publicly)
--inspect-wait wait for a debugger to attach, then run (Node 22.2+)

Then open chrome://inspect in Chrome and click inspect under your script. You get the familiar DevTools: breakpoints, step over/into/out, watch expressions, the call stack and a console that runs code in the paused scope.

You can also hard-code a breakpoint with the debugger statement — it pauses only when a debugger is attached, and is ignored otherwise:

js
function applyDiscount(cart) {
  debugger;                // execution stops here under --inspect
  return cart.total * 0.9;
}

Debugging in VS Code

VS Code has the Node debugger built in. The easiest way: open the JavaScript Debug Terminal (Command Palette → "Debug: JavaScript Debug Terminal") and run your program normally with node app.js or npm start — breakpoints you set by clicking left of the line numbers just work. For repeatable setups, a .vscode/launch.json file stores the configuration:

json
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug app",
      "program": "${workspaceFolder}/app.js",
      "envFile": "${workspaceFolder}/.env"
    }
  ]
}

Other handy tools

  • node --watch app.js restarts your program whenever a file changes — great while fixing a bug.
  • NODE_DEBUG=http,net node app.js makes core modules print internal debug logs.
  • util.debuglog('mymodule') lets your code print debug messages only when NODE_DEBUG=mymodule is set.
  • node --trace-warnings shows where a warning (like a deprecation) came from.

A debugging checklist

  1. Reproduce the bug reliably, ideally with a small input.
  2. Read the full error message and the top frames of the stack trace.
  3. Form a guess and check it — print the value or set a breakpoint just before the failing line.
  4. Fix one thing at a time, then write a test so the bug can't come back.

Test yourself

Which flag starts Node with the debugger and pauses on the first line?

  1. --debug
  2. --inspect-brk
  3. --pause
  4. --trace

How do you print a deeply nested object completely?

  1. console.log(obj, true)
  2. console.dir(obj, { depth: null })
  3. console.deep(obj)
  4. JSON.print(obj)

What does the debugger statement do when no debugger is attached?

  1. Throws an error
  2. Pauses forever
  3. Nothing — it is ignored
  4. Prints the stack trace