Debugging Node Apps: Breakpoints, --inspect and Reading Stack Traces

Node.js and Express: Build a Back End API from Scratch · Testing, Debugging and Deployment · 5 min read · Updated

From wrong answer to cause

  1. The result is wrong but nothing crashed, so there is no stack trace to read.
  2. Set a breakpoint on the suspicious line and run in the debugger.
  3. Look at the real values. One amount is the text 250, so adding joins text instead of adding numbers.
  4. Fix the cause, validate the input, and write a test so the bug cannot return.

Beginners debug by adding console.log everywhere, running again, and reading a wall of output. It works for small problems. For anything harder, the faster tool is a debugger: it pauses your program at a line you choose and lets you look at every variable at that moment. Learning it early repays you for the rest of your career. This lesson shows how, with a small file that has a real, typical bug in it.

Read the error first

When Node crashes it prints a stack trace: the error message, then the chain of function calls that led to it, newest first. Read it in this order. First, the message and the error type, for example TypeError: Cannot read properties of undefined (reading 'name'). It tells you what went wrong. Second, the first line of the trace that points to *your* file, not to node_modules or node:internal. It tells you where. Then look at that line and ask what could be undefined or the wrong type there. Half of all bugs end here.

  • ReferenceError: you used a name that does not exist, often a typo or a missing import.
  • TypeError: you used a value in a way it does not allow, often because it is undefined or null.
  • ERR_MODULE_NOT_FOUND or Cannot find module: a wrong path or a missing package.
  • EADDRINUSE: another process already uses that port.
  • UnhandledPromiseRejection: a promise failed and nothing handled it.

A bug to practise on

The function below should return the average of the order amounts. The result is wrong, and no error appears, which is exactly the kind of bug where a debugger helps.

// A function with a bug. Use it to practise the debugger:  node --inspect-brk d41-bug.js
export function averageOrderValue(orders) {
  let total = 0;
  for (const order of orders) {
    total += order.amount;          // set a breakpoint here and watch "total" and "order"
  }
  return total / orders.length;
}

const orders = [{ amount: 100 }, { amount: '250' }, { amount: 50 }];   // BUG: one amount is a string
console.log(averageOrderValue(orders));
node d41-bug.js
3341683.3333333335

An average of three orders worth about a hundred each should be near 133, not more than three million. Do not guess. Use the debugger.

Debugging in VS Code

  1. Open the folder in VS Code and open the file.
  2. Click in the left margin next to the line total += order.amount;. A red dot, a breakpoint, appears.
  3. Open the *Run and Debug* panel and choose *Run and Debug*, then *Node.js*. The program runs and pauses on your line.
  4. Look at the Variables panel. order is { amount: 100 } and total is 0. Press Continue twice more. On the second round, order.amount is the text '250', and total becomes the text '100250'.
  5. Now you see it: adding a number and a string in JavaScript joins them as text. Fix it by converting with Number(order.amount), or better, by validating the data when it enters, as in lesson 26.

The useful controls are: Step over, run this line and stop at the next; Step into, go inside the function that this line calls; Step out, finish the current function; and Continue, run until the next breakpoint. The Watch panel lets you type an expression such as typeof order.amount and see it update. A conditional breakpoint, set by right-clicking the red dot, pauses only when a condition is true, for example order.amount === '250'. That is the tool for the bug that appears only on record 8,000.

Debugging with --inspect

Node has a debugger built in. Run node --inspect-brk d41-bug.js; -brk pauses at the first line. Then open chrome://inspect in Chrome, click *inspect* below your process, and the same stepping tools open in Chrome DevTools. This also works for a server that runs on another machine, when you forward the port through an SSH tunnel. Never open the debug port to the internet. Anyone who connects can run any code on your server.

Habits that save hours

  • Make the bug reproducible before anything else. A bug that you can trigger on demand is half solved.
  • Change one thing at a time, and test after each change.
  • Shrink the problem: remove code until the smallest example still fails.
  • Read the error message slowly and completely. Most of the answer is in it.
  • Write a test for the bug before you fix it, so that it can never return unnoticed.
  • Explain the problem aloud to someone, or to a rubber duck. This habit is famous because it works.

Your task

  1. Fix the bug with Number(order.amount) and also add a check that rejects an amount that is not a number.
  2. Put a conditional breakpoint that stops only when typeof order.amount === 'string'.
  3. Start a small Express server with node --inspect and attach Chrome DevTools to it.

How to check it worked

  • You found the string '250' with a breakpoint and not by guessing.
  • You can say what step over and step into do.
  • You know why the debug port must never be public.

Frequently asked questions

Is console.log wrong?

No, it is quick and useful. A debugger is better when you need to see many values at one moment, or step through unknown code.

What is a breakpoint?

A marker on a line where the program pauses so that you can look at its variables and step forward.

Why is it dangerous to expose the inspect port?

Anyone who can connect to it can run code inside your process. Keep it on localhost and use an SSH tunnel.

Practise with interview questions