Debugging and Performance

Back

Loading concept...

đź”§ Node.js Debugging & Performance: Your Detective Toolkit

The Analogy: Think of your Node.js app as a busy kitchen. Sometimes dishes take too long, sometimes things break. You need tools to figure out what’s slow and what’s broken. That’s what debugging and performance tools are for—they’re your kitchen cameras and timers!


🎯 What We’ll Learn

  1. perf_hooks overview – Your stopwatch collection
  2. performance.now – The super-precise timer
  3. Debugging Node.js – Finding what’s broken
  4. Debug mode flags – Turning on special lights
  5. Chrome DevTools integration – Using the fancy control room
  6. Event loop blocking detection – Finding the traffic jam

1. 📊 perf_hooks Overview

What is it?

Imagine you have a box of stopwatches. Each one can time different parts of your kitchen work. That’s perf_hooks—Node.js’s built-in timing toolkit!

The Story

Little Chef needs to know which recipe step takes longest. She opens her stopwatch box (perf_hooks) and picks the right timer for each task.

Simple Example

const { performance } = require('perf_hooks');

// Start cooking
const start = performance.now();

// Do some work (like chopping)
let sum = 0;
for (let i = 0; i < 1000000; i++) {
  sum += i;
}

// Stop timer
const end = performance.now();
console.log(`Took ${end - start} ms`);

What’s Inside the Box?

graph TD A["perf_hooks"] --> B["performance.now"] A --> C["PerformanceObserver"] A --> D["performance.mark"] A --> E["performance.measure"] style A fill:#667eea,color:white
Tool What It Does
performance.now() Super precise timer
performance.mark() Puts a flag in time
performance.measure() Measures between flags
PerformanceObserver Watches for timing events

2. ⏱️ performance.now()

What is it?

The most precise stopwatch in your toolkit. It tells time in milliseconds with decimal points—way more accurate than a regular clock!

Why It’s Special

Regular Date.now() tells time in whole milliseconds. But performance.now() can measure tiny fractions—perfect for finding small slowdowns.

Simple Example

const { performance } = require('perf_hooks');

// Measure how long a function takes
function slowFunction() {
  let result = 0;
  for (let i = 0; i < 100000; i++) {
    result += Math.sqrt(i);
  }
  return result;
}

const before = performance.now();
slowFunction();
const after = performance.now();

console.log(`Time: ${after - before} ms`);
// Output: Time: 2.345678 ms

🎯 Key Point

  • Date.now() → “It’s 3:45 PM”
  • performance.now() → “It’s 3:45:32.567891 PM”

The second one helps you find tiny delays!


3. 🔍 Debugging Node.js

What is it?

Debugging means finding and fixing problems in your code. It’s like being a detective looking for clues!

The Story

Your recipe isn’t working. The cake is flat. You need to pause, look at each ingredient, and find where things went wrong. That’s debugging!

Three Ways to Debug

graph TD A["Debugging Methods"] --> B["console.log"] A --> C["debugger keyword"] A --> D["Node Inspector"] B --> E["Quick &amp; Easy"] C --> F["Pause &amp; Examine"] D --> G["Full Control"] style A fill:#FF6B6B,color:white

Method 1: console.log (The Quick Way)

function calculateTotal(items) {
  console.log('Items received:', items);

  let total = 0;
  for (let item of items) {
    console.log('Adding:', item.price);
    total += item.price;
  }

  console.log('Final total:', total);
  return total;
}

Method 2: debugger Keyword

function findBug(data) {
  let result = [];

  for (let item of data) {
    debugger; // Code STOPS here!
    // Now you can look at 'item'
    result.push(item * 2);
  }

  return result;
}

🎯 When to Use What

Situation Best Tool
Quick check console.log
Complex bug debugger + DevTools
Production issue Node Inspector

4. 🚦 Debug Mode Flags

What is it?

Special switches you flip when starting Node.js to turn on detective mode. Like turning on special lights in the kitchen to see hidden dirt!

The Main Flags

graph TD A["Debug Flags"] --> B["--inspect"] A --> C["--inspect-brk"] A --> D["NODE_DEBUG"] B --> E["Opens debugging port"] C --> F["Stops at first line"] D --> G["Shows internal logs"] style A fill:#4ECDC4,color:white

Flag 1: --inspect

Opens the door for Chrome DevTools to connect.

node --inspect app.js

Output:

Debugger listening on ws://127.0.0.1:9229

Flag 2: --inspect-brk

Same as --inspect, but pauses at the very first line. Perfect when the bug happens early!

node --inspect-brk app.js

Flag 3: NODE_DEBUG

Shows hidden messages from Node.js internals.

NODE_DEBUG=http node app.js

This shows what’s happening inside HTTP!

Simple Example

# Normal run - no debug info
node server.js

# Debug mode - Chrome can connect
node --inspect server.js

# Debug mode - stops immediately
node --inspect-brk server.js

# Show HTTP internal logs
NODE_DEBUG=http node server.js

5. 🖥️ Chrome DevTools Integration

What is it?

Chrome DevTools is like a fancy control room for your code. You can pause, step through, and see everything happening!

How to Connect

graph TD A["Start Node with --inspect"] --> B["Open Chrome"] B --> C["Go to chrome://inspect"] C --> D["Click &&#35;39;Open dedicated DevTools&&#35;39;"] D --> E[🎉 You're connected!] style E fill:#667eea,color:white

Step-by-Step

Step 1: Start your app with inspect flag

node --inspect app.js

Step 2: Open Chrome browser

Step 3: Type in address bar:

chrome://inspect

Step 4: Click “Open dedicated DevTools for Node”

What You Can Do

Feature What It Does
Sources See your code, add breakpoints
Console Run commands, see logs
Profiler Find slow functions
Memory Find memory leaks

Simple Example

// app.js
const http = require('http');

const server = http.createServer((req, res) => {
  debugger; // DevTools will pause here!
  res.end('Hello World');
});

server.listen(3000);

Run with:

node --inspect app.js

Now Chrome shows you everything when a request comes in!


6. đźš§ Event Loop Blocking Detection

What is it?

The event loop is Node.js’s heart—it keeps everything running smoothly. When something blocks it, everything freezes. Like if one chef takes over the whole kitchen!

The Story

Imagine a restaurant with one waiter (event loop). If someone orders something that takes 10 minutes to prepare, everyone else waits. That’s blocking!

What Causes Blocking?

graph TD A["Blocking Causes"] --> B["Heavy calculations"] A --> C["Sync file operations"] A --> D["Long loops"] A --> E["JSON.parse on huge data"] style A fill:#FF6B6B,color:white

How to Detect It

Method 1: Using monitorEventLoopDelay

const {
  monitorEventLoopDelay
} = require('perf_hooks');

// Create a monitor
const monitor = monitorEventLoopDelay();
monitor.enable();

// Check after some time
setTimeout(() => {
  console.log('Min delay:', monitor.min);
  console.log('Max delay:', monitor.max);
  console.log('Mean delay:', monitor.mean);

  // If max is high, something blocked!
  if (monitor.max > 100) {
    console.log('⚠️ Event loop was blocked!');
  }
}, 5000);

Method 2: Simple Timer Check

let lastCheck = Date.now();

setInterval(() => {
  const now = Date.now();
  const delay = now - lastCheck - 1000;

  if (delay > 50) {
    console.log(`⚠️ Blocked for ${delay}ms!`);
  }

  lastCheck = now;
}, 1000);

Good vs Bad Code

❌ Blocking Code:

// BAD - Blocks the event loop
const data = fs.readFileSync('huge-file.txt');

âś… Non-Blocking Code:

// GOOD - Doesn't block
fs.readFile('huge-file.txt', (err, data) => {
  // Handle data here
});

🎯 Summary: Your Debugging Toolkit

Tool When to Use
perf_hooks Measure any timing
performance.now() Super precise timing
console.log Quick debugging
--inspect Connect Chrome DevTools
--inspect-brk Debug from the start
NODE_DEBUG See Node internals
monitorEventLoopDelay Find blocking code

🌟 Remember

Debugging is like being a detective. You have the tools. You have the clues. Now go solve the mystery!

graph TD A["🔧 Debug Tools"] --> B["Find the Problem"] B --> C["Understand Why"] C --> D["Fix It"] D --> E["🎉 Success!"] style E fill:#4ECDC4,color:white

You’ve got this! Every great developer debugs. The difference is having the right tools—and now you do! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.