iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Debugging

Node has had a real debugger for years - learn the inspector protocol, breakpoints, and how to attach VS Code or Chrome DevTools instead of console.log everything.

Node debugging fundamentals

EXAMPLE
// 1. Start with the inspector
//    node --inspect server.js              -> connect at startup
//    node --inspect-brk server.js          -> break on first line
//    node --inspect=0.0.0.0:9229 server.js -> bind for remote

// 2. Attach Chrome DevTools
//    Open chrome://inspect, click 'Open dedicated DevTools for Node'

// 3. VS Code launch.json
{
  'version': '0.2.0',
  'configurations': [
    {
      'type': 'node',
      'request': 'launch',
      'name': 'Launch server',
      'runtimeArgs': ['--enable-source-maps'],
      'program': '${workspaceFolder}/src/server.ts',
      'skipFiles': ['<node_internals>/**'],
      'console': 'integratedTerminal'
    },
    {
      'type': 'node',
      'request': 'attach',
      'name': 'Attach to running',
      'port': 9229
    }
  ]
}

// 4. Useful breakpoints
debugger;  // unconditional - removed in production builds

// 5. Conditional breakpoints in DevTools/VS Code
//    Right-click margin -> Add Conditional Breakpoint -> orderId === 'ord_42'

// 6. Async stack traces are on by default since Node 12+

// 7. CPU profile from CLI
//    node --cpu-prof server.js   -> writes isolate-*.cpuprofile
//    Load it in Chrome DevTools Performance tab

// 8. Heap snapshot
const v8 = require('v8');
require('fs').writeFileSync(
  'heap-' + Date.now() + '.heapsnapshot',
  v8.writeHeapSnapshot()
);

// 9. NODE_OPTIONS for production
//    NODE_OPTIONS='--enable-source-maps --max-old-space-size=2048' node dist/server.js

Why it matters

console.log is fine for one or two lines. Beyond that you are reverse-engineering your own program. Learn the inspector once and never go back - especially for async stack traces, conditional breakpoints, and heap profiles you cannot get from logs.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
node --inspect-brk src/index.js
// then open chrome://inspect or use your IDE
Try it Yourself »

Discussion

Loading…