Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 133 ยท Compression, CLI and Tooling

Debugging and Diagnostics

Debug Node.js programs - read stack traces and error.cause chains, use --inspect and debugger, util.debuglog, diagnostics_channel, process reports, source maps and async stack traces.

Every program has bugs, and the difference between a frustrating afternoon and a five-minute fix is usually how good you are at looking. Node.js gives you far more tools for looking than console.log: stack traces that cross await, a built-in debugger protocol, switchable debug logging, event channels that libraries publish to, and reports that capture the state of a process at the moment it went wrong.

This lesson goes through them in the order you will need them: first reading an error properly, then the interactive debugger, then the lighter tools that work in production. Some tools need command-line flags or a debugger window, which our editor cannot give you, so those appear as read-only snippets that describe what you would see on your own machine. Everything else runs right here. It follows on from Errors and Error Handling and pairs with Logging and Observability and V8, Memory and Garbage Collection.

Reading a stack trace

A stack trace is the list of function calls that were active when an error was created, most recent first. Learn to read it like a sentence. Take the first line that points into your code (skip lines from node:internal/...), and you usually have the place to look.

Each line has the shape at functionName (file:line:column). Modern Node.js also shows async frames: when an error passes through await, the trace includes the awaiting functions marked with async, so you can follow the story across promises, not just across synchronous calls. This is built into V8 and costs almost nothing.

Node.js A stack trace that crosses await

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read it from the top: the error is a TypeError created in parsePrice (line 4), called by loadItem, which was awaited by loadCart, which was awaited by the top level. The word async marks frames that were resumed after an await. If you see only the top few frames, a bare then chain or an old callback API probably cut the history, which is another reason to prefer async/await (see async/await).

Two properties are worth knowing:

  • Error.stackTraceLimit (default 10) caps how many frames are recorded. Raise it while hunting a bug in deep code, or lower it to save work in hot paths that create many errors.
  • Error.captureStackTrace(target) fills in a stack property on any object, which is how libraries build custom errors that hide their own helper frames.
Node.js stackTraceLimit and captureStackTrace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the last example the trace starts at register, the code that made the mistake, instead of inside the validation helper.

Error causes

When one error leads to another, do not throw away the first. Pass it as the cause option when you wrap it: new Error('message', { cause: original }). The original stack is kept, and console.log and the uncaught-exception printer show the whole chain under [cause].

Node.js Wrapping an error and keeping its cause

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For code that collects several failures at once (for instance Promise.any or a validator), AggregateError carries an errors array in the same spirit. When you log in production, log the entire chain: the outermost message tells you what you were trying to do, and the innermost cause tells you why it failed.

The interactive debugger

Printing values works until the problem involves many variables or a long flow. A debugger lets you pause the program, look at every variable, step line by line and even change values. Node.js speaks the Chrome DevTools Protocol, so you can use Chrome, Edge, VS Code, WebStorm and others.

You start it with a flag. These commands run on your own machine (read-only here, since we cannot add flags in the editor):

Terminal
# Start normally but listen for a debugger on 127.0.0.1:9229
node --inspect server.js

# Pause on the very first line, waiting for you to attach
node --inspect-brk server.js

# Built-in command-line debugger (no browser needed)
node inspect server.js

# Attach to an already running process (Linux/macOS)
kill -USR1 <pid>

With --inspect, open chrome://inspect in Chrome (or edge://inspect), click "inspect" under your Node target, and the DevTools window shows your source, a variable panel and a call stack. In VS Code, the "JavaScript Debug Terminal" attaches automatically to any node you start there, and launch configurations let you press F5.

What can you do once attached?

  • Breakpoints: click a line number to pause when execution reaches it. A conditional breakpoint pauses only when an expression is true (user.id === 42), and a logpoint prints a message without changing your code.
  • Step controls: step over (next line), step into (enter the call), step out (finish this function).
  • Watch and scope panels: see every variable in scope and evaluate expressions in the paused context.
  • Pause on exceptions: stop at the exact throw, even if it is caught later. This is the fastest way to find where an error began.
  • Memory and CPU profiles: the same window records heap snapshots (see V8, Memory and Garbage Collection) and CPU profiles that show which functions use the time.

The debugger; statement is a breakpoint written in code. If no debugger is attached, it does nothing, so it is harmless to run (though you should remove it before committing).

Never expose the inspector port to a network. Anyone who can reach port 9229 can run arbitrary code in your process. The default --inspect binds to localhost only; leave it that way, and use an SSH tunnel to debug a remote machine. The flag --inspect=0.0.0.0 on a public server is an open door.

The inspector is also available from inside your program, as the node:inspector module. That is how profilers work, and it shows what the protocol looks like. The next example connects a session to its own process and asks it to evaluate an expression.

Node.js Talking to the inspector from code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The callback runs synchronously inside post for in-process sessions, so the result appears first. For day-to-day debugging you will rarely write this yourself, but it is useful to know that the "debugger" is just a protocol over a socket or a function call.

Switchable debug logging: util.debuglog

Sprinkling console.log calls that you later delete is tedious. A better habit is to leave debug logging in the code and turn it on only when needed. util.debuglog(section) returns a function that prints to stderr only if the environment variable NODE_DEBUG contains that section name. Node's own modules use the same system: NODE_DEBUG=http,net node app.js prints what the HTTP and net layers are doing.

The check happens once per call and costs almost nothing when disabled. The next example runs the same tiny script three times with different values of NODE_DEBUG, so you can see the switch working. (The messages are prefixed with the section name and the process id; we remove the id because it changes every run.)

Node.js NODE_DEBUG switches debuglog on and off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Section names are matched case-insensitively and may use a trailing * as a wildcard. Use one section per component (myapp:db, myapp:cache) so you can switch on just the area you are investigating. For application logging that must always be recorded, use a real logger instead (see Logging and Observability).

diagnostics_channel: events for tools

node:diagnostics_channel is a publish/subscribe system built for observability. A library creates a named channel and publishes messages describing what happens inside it (a query started, a request arrived). Monitoring tools subscribe and use the messages without patching the library. Node's own HTTP, net and fetch (undici) implementations publish channels such as http.client.request.start.

The design goal is zero cost when nobody listens: channel.hasSubscribers is cheap to check, and a publisher can skip building the message entirely.

Node.js Publishing and subscribing to a channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For measuring operations that take time, tracingChannel wraps a function and publishes start, end, asyncStart, asyncEnd and error events with one shared context object. That is how tracing tools build spans without touching your code.

Node.js tracingChannel around an async function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the order for the failing call: the error event fires first, then asyncStart and asyncEnd (with no result), and the caller still receives the rejection. Because the channel does nothing unless a subscriber exists, you can add tracing to your own libraries without slowing them down.

Process reports

When a production process misbehaves (it hangs, crashes or uses too much memory), you want a snapshot of everything: the JavaScript and native stacks, the heap statistics, active handles, operating-system details and library versions. Node.js can write that as one JSON file, called a diagnostic report.

You can trigger one from code with process.report.writeReport(), or ask Node to write one automatically on certain events using flags (read-only here):

Terminal
# Write a report on a crash, an uncaught exception, or when the process receives SIGUSR2
node --report-on-fatalerror --report-uncaught-exception --report-on-signal --report-signal=SIGUSR2 \
     --report-directory=/var/reports server.js

Reading a report starts with its top-level sections. We can get one in memory with process.report.getReport(), and passing an error makes it use that error's stack. Reports contain environment variables and host details, so treat them as sensitive and never post them publicly.

Node.js What is inside a diagnostic report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The libuv section lists the active handles and requests (open sockets, timers, file operations). When a process refuses to exit, this list shows what is keeping it alive. The same idea is behind process.getActiveResourcesInfo(), which returns the names of active resources in a single call.

Source maps

Much production code is not what you wrote. TypeScript is compiled to JavaScript, and bundlers combine and shrink files. When an error happens, the stack trace points at the generated file, line 1, column 30000, which is useless. A source map is a JSON file that maps positions in the generated code back to your original files.

Node.js applies source maps to stack traces if you start it with --enable-source-maps (our editor does this already; the flag has a small performance cost, so decide per service). The example below builds a tiny generated file and a hand-written source map that claims "line 1 of this file came from line 10 of src/checkout.ts", then runs it twice in child processes so you can compare the traces.

Node.js Stack traces with and without source maps (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without the flag the trace names bundle.cjs; with it, Node reports src/checkout.ts:10:1. For TypeScript run directly by Node (see Running TypeScript in Node.js), types are stripped without moving lines, so traces already point to the right place.

Related flags you will meet: --stack-trace-limit=N, --trace-uncaught (prints where uncaught exceptions were thrown), --trace-warnings (shows the stack behind a warning such as a deprecation) and --trace-deprecation. All read-only here, but very handy on the command line:

Terminal
node --trace-warnings app.js          # where does this warning come from?
node --trace-uncaught app.js          # where was the thrown value created?
node --unhandled-rejections=strict app.js

A debugging checklist

When something fails and you do not know why, work through these steps in order. They find most problems quickly.

  1. Read the whole error, not only the first line. Follow [cause] to the innermost error and find the first frame in your own code.
  2. Reproduce it small. Remove code until the failure goes away, then put back the last piece. A short reproduction is half of the fix.
  3. Check assumptions with data. Log the actual values at the boundary (console.log(JSON.stringify(input)), or console.dir(value, { depth: null })) before guessing.
  4. Use the debugger for flow problems, with "pause on exceptions" enabled, and logpoints instead of edited console.log lines.
  5. Turn on NODE_DEBUG sections for networking or module problems (NODE_DEBUG=net,http,module).
  6. For hangs, ask what is still active: process.getActiveResourcesInfo() or a diagnostic report. For memory growth, take heap snapshots.
  7. For production-only bugs, add structured logs with correlation ids, subscribe to diagnostics channels, and keep source maps available.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a stack trace, what does the word async before a function name tell you?

    V8 reconstructs async stack frames across await, so you can see which functions were waiting for which.
  2. 2. How do you keep the original error when you throw a new, more descriptive one?

    The cause option stores the original error on error.cause, and Node prints the whole chain under [cause].
  3. 3. What is the risk of running node --inspect=0.0.0.0 on a public server?

    The inspector protocol allows evaluating arbitrary code. Bind to localhost and tunnel (for example over SSH) when you must debug remotely.
  4. 4. When does a util.debuglog('db') call print its message?

    debuglog writes to stderr only if NODE_DEBUG enables its section, so it can stay in the code at almost no cost.
  5. 5. Why does channel.hasSubscribers matter in diagnostics_channel?

    Checking hasSubscribers is cheap, so instrumented libraries cost almost nothing unless a monitoring tool subscribes.

Summary

  • Read stack traces from the top, skip node:internal frames, and use async frames to follow the story across await; adjust Error.stackTraceLimit and use Error.captureStackTrace when building error helpers.
  • Wrap errors with new Error(message, { cause }) so the full chain survives and is printed under [cause].
  • node --inspect (or --inspect-brk, node inspect) lets Chrome DevTools, VS Code and others set breakpoints, step through code and take profiles; the debugger; statement is a breakpoint in code. Never expose the inspector port publicly.
  • util.debuglog(section) prints to stderr only when NODE_DEBUG enables the section.
  • diagnostics_channel and tracingChannel let libraries publish events for monitoring tools at near-zero cost when nobody listens.
  • Process reports capture JavaScript and native stacks, heap data and active handles; use --report-* flags or process.report.getReport().
  • --enable-source-maps turns traces of compiled or bundled code back into your original file names and lines.

Next: Express and Minimal Frameworks