Debugging Node.js Applications

1. Using console.log for Debugging

TipDetail
Tagged logsconsole.log("[user]", user)
Inspect deeplyconsole.dir(obj, { depth: null, colors: true })
Tablesconsole.table(rows)
Traceconsole.trace("got here")

2. Using debugger Statement

StatementEffect
debugger;Pauses when an inspector is attached

3. Using Node Inspector (--inspect flag)

FlagBehavior
--inspectListen on 127.0.0.1:9229
--inspect=0.0.0.0:9229Bind specific addr
--inspect-waitWait for debugger before script start v22+

4. Using node --inspect-brk

FlagBehavior
--inspect-brkPause on first line until debugger connects

5. Using Chrome DevTools (chrome://inspect)

Connect Workflow

  1. Run node --inspect-brk app.js
  2. Open chrome://inspect in Chrome/Edge
  3. Click "Inspect" on the listed target
  4. Use Sources, Profiler, Memory tabs

6. Using VS Code Debugger (launch.json)

Example: launch.json

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Debug app",
      "program": "${workspaceFolder}/src/index.js",
      "skipFiles": ["<node_internals>/**"],
      "env": { "NODE_ENV": "development" }
    },
    { "type": "node", "request": "attach", "name": "Attach", "port": 9229 }
  ]
}

7. Using Debug Module

Example

import createDebug from "debug";
const debug = createDebug("app:db");
debug("query %o", q);
// DEBUG=app:* node app.js

8. Setting Breakpoints

TypeDescription
LineClick gutter in DevTools/VS Code
ConditionalBreak only when expression is true
LogpointPrint without pausing
ExceptionPause on caught/uncaught throws

9. Profiling CPU Usage (--prof flag)

FlagEffect
--profGenerates V8 tick log file
--cpu-profWrites .cpuprofile (DevTools)
--cpu-prof-dir=./profsOutput directory

10. Analyzing Profile Output (--prof-process)

Example

node --prof app.js
node --prof-process isolate-*.log > report.txt

11. Memory Leak Detection

ToolUse
Heap snapshotsv8.writeHeapSnapshot() + Chrome DevTools
--heap-profSampling heap profile
--inspect + Memory tabCompare snapshots
Common causesListener leaks, growing caches, closures over big objects

12. Using Clinic.js for Diagnostics

ToolDiagnoses
clinic doctorSymptom-based analysis
clinic flameFlamegraph (CPU)
clinic bubbleprofAsync bottlenecks
clinic heapprofilerHeap allocation

13. Using llnode for Post-Mortem Debugging

ToolUse
llnodeLLDB plugin to inspect Node core dumps
--abort-on-uncaught-exceptionGenerate core dump on crash