Debugging: console, the stack and the inspector
A program that prints nothing is not fixed by guessing. The three tools of this lesson are the ones that answer the question what is it doing without a debugger: the two streams that separate data from messages, the table that shows a list at a glance, and the stack trace that names the frames of a failure.
The last section adds the debugger itself. Node.js can open a debugging protocol on a port that an editor or a browser connects to, and the same protocol is a module a program can call, which is the part that can be shown in a block of output here.
Standard output and standard error
console.log writes to standard output and console.error to standard error, which is a second stream that a pipe leaves alone by default. The difference matters in a program whose output is data: the reader of the pipe gets the values, and the messages stay in the terminal where a person sees them.
The file streams.mjs:
console.log('a line for the output');
console.error('a line for the errors');
console.warn('a line for warnings');
console.log('the last line');
node streams.mjs 2>&1
a line for the output
a line for the errors
a line for warnings
the last line
With both streams on the terminal the four lines appear in the order they were written, and nothing shows which one went where. The same file with standard error redirected shows the split:
node streams.mjs 2>/dev/null
a line for the output
the last line
console.warn went to the same stream as console.error, which is why both lines disappeared. A program that prints its result with console.log and its progress with console.error can be piped into another program and still show the progress to the person who runs it.
console.table
A list of objects read as lines of text is hard to compare. console.table takes an array and prints one row per element with one column per field, which makes an off-by-one in a price or a quantity visible at once. The index column is the position, and the quotes mark the strings.
The file table.mjs:
const rows = [
{ name: 'pencil', price: 50, quantity: 10 },
{ name: 'coffee', price: 800, quantity: 2 },
];
console.table(rows);
node table.mjs
┌─────────┬──────────┬───────┬──────────┐
│ (index) │ name │ price │ quantity │
├─────────┼──────────┼───────┼──────────┤
│ 0 │ 'pencil' │ 50 │ 10 │
│ 1 │ 'coffee' │ 800 │ 2 │
└─────────┴──────────┴───────┴──────────┘
The columns are the union of the keys, and a row that lacks one leaves a gap rather than a wrong value, which is itself useful to see. The output is for a person, not for a pipe: it is drawn with box characters and aligned for a terminal of any width, so a program that needs a stable output writes its own format instead.
Reading a stack trace
The stack is a string with one frame per line. The first line is the name and the message of the error, and the frames below it begin with the innermost call and end with the code of the runtime. The frames of the file that threw are the ones to read, and the program below picks them out of the string.
The file stack.mjs:
function inner() {
throw new Error('this is the failure');
}
function middle() {
inner();
}
function outer() {
middle();
}
try {
outer();
} catch (error) {
const lines = error.stack.split('\n');
console.log('the first line:', lines[0]);
console.log('the frames in this file:');
for (const line of lines.slice(1)) {
const match = line.match(/at (\w+) \(/);
if (match && line.includes('stack.mjs')) {
console.log(` ${match[1]}`);
}
}
}
node stack.mjs
the first line: Error: this is the failure
the frames in this file:
inner
middle
outer
The innermost frame is inner, the one that threw, and the caller of each frame comes next, which is why the list reads upwards towards the code that started the work. The frames of the runtime were filtered out by the file name, and the frames without a function name, such as the top level of a module, were skipped by the pattern: a real trace has both, and they are the reason a trace looks longer than the program.
node --inspect
node --inspect file.mjs starts the program and opens a debugging protocol on a local port; --inspect-brk also stops on the first line, before anything runs. An editor connects to that port, sets breakpoints and reads the values of the variables. The line the runtime prints when it opens the port contains a one-time id, so this page does not copy it.
The protocol is also a module, and a program can talk to its own runtime with it. The one below connects a session, asks the engine to evaluate an expression, prints the answer and closes the session, which is the same call an editor makes when it shows a value at a breakpoint.
The file inspector.mjs:
import { Session } from 'node:inspector/promises';
const session = new Session();
session.connect();
const result = await session.post('Runtime.evaluate', { expression: '2 + 2' });
console.log('the inspector evaluated:', result.result.value);
session.disconnect();
console.log('the session is closed');
node inspector.mjs
the inspector evaluated: 4
the session is closed
The value came back as a protocol message with a type and a value, and the program printed the field it wanted. That is the shape of every debugger: a client sends a command such as Runtime.evaluate or Debugger.setBreakpoint, and the runtime answers with a message. The next lesson leaves the debugging and starts the part of the course about code that does not run in one go.
Exercises
- Add a console.error line to the table program and run it with standard error on a file. Which file gets which line?
- Print a table of three objects with different keys and see which gaps appear.
- Change the filter in the stack program to print every frame, including those of the runtime. How many frames does a small file like this one produce?
- Print only the file name and the line of each frame of the stack, using a pattern that reads both.
- Ask the inspector session for process.version and print the value. What does the protocol answer when the expression throws?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which console method writes to standard error?
Answer
console.error
console.error and console.warn use the second stream, which a pipe leaves alone by default.
-
Why keep messages on standard error and data on standard output?
Answer
A pipe reads the data alone, and the messages stay visible
Redirecting one stream leaves the other, so a program can be both a pipeline step and readable.
-
What does console.table take?
Answer
An array of objects, one row each
The keys become the columns and the elements become the rows.
-
Which frame of a stack trace is the one that threw?
Answer
The first frame below the message
The trace starts at the innermost call and walks outwards to the code that started it.
-
What does this program print?
try { throw new Error("bad"); } catch (error) { console.log(error.stack.split("\n")[0]); }Answer
Error: bad
The trace begins with the name, a colon and the message, and the frames follow.
-
What does this program print?
function a() { b(); } function b() { throw new Error("deep"); } try { a(); } catch (error) { const frame = error.stack.split("\n")[1].trim(); console.log(frame.startsWith("at b")); }Answer
true
The innermost frame is the one that threw, and it names the function b.
-
What does node --inspect do?
Answer
It opens a debugging protocol on a port for a client
The runtime listens on a local port, and an editor or a browser connects to it.
-
What does --inspect-brk add?
Answer
It stops on the first line, before the program runs
The break at the start gives the client time to connect before the first statement runs.
-
What does a Session from node:inspector/promises let a program do?
Answer
Send protocol commands to its own runtime
The session is the client half of the protocol, connected to the same process.
-
Which line of a stack trace should be read first?
Answer
The message, then the first frame of your own file
The message names the failure and the first own frame names where it happened.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev