Debugging
Inspect running code with the built-in Node debugger.
Syntax
node --inspect app.jsBeyond console.log, Node has a real debugger. Start your program with the --inspect flag and connect Chrome DevTools or your editor to set breakpoints and step through code.
Options
node --inspect app.js— attach a debugger.node --inspect-brk app.js— pause on the first line.- The
debugger;statement — a breakpoint in code.
Example
function calculate(a, b) {
const sum = a + b;
debugger; // execution pauses here under --inspect
return sum * 2;
}
console.log(calculate(3, 4)); // 14When to use it
- A developer uses `node --inspect` and Chrome DevTools to set breakpoints inside an Express middleware that processes malformed JSON payloads.
- A CI pipeline runs tests with `--inspect-brk` so a developer can remotely attach a debugger the moment a flaky test begins.
- An SRE uses `node --prof` to generate a CPU profile of a production-like workload, then `node --prof-process` to find the hot function causing high latency.
More examples
Start the Node.js inspector
Launches Node with the V8 inspector enabled -- open `chrome://inspect` to attach Chrome DevTools.
# Attach Chrome DevTools at chrome://inspect
node --inspect server.js
# Break on the first line (wait for debugger)
node --inspect-brk server.jsDebug with VS Code launch config
A VS Code `launch.json` configuration that starts the app with the debugger attached and loads env vars.
{
"version": "0.2.0",
"configurations": [{
"type": "node",
"request": "launch",
"name": "Debug API",
"program": "${workspaceFolder}/src/index.js",
"envFile": "${workspaceFolder}/.env"
}]
}Conditional debug logging
Uses the `debug` package to emit namespaced log lines that are silent by default and enabled via the `DEBUG` env var.
const debug = require('debug')('app:auth');
function verifyToken(token) {
debug('Verifying token: %s', token.slice(0, 8));
// ...
}
// Enable in shell:
// DEBUG=app:auth node server.js
Discussion