4️⃣ Event-Driven Architecture

How Node.js Handles Concurrency

📝 Note: This is a short section to help you understand how Node.js works internally. No deep theory needed!

4.1 EventEmitter

Node.js uses events extensively. Many built-in objects emit events that you can listen to.

Basic EventEmitter Example

// events-example.js
const EventEmitter = require('events');

// Create an event emitter
const emitter = new EventEmitter();

// Listen for 'orderPlaced' event
emitter.on('orderPlaced', (order) => {
  console.log('📧 Sending confirmation email for order:', order.id);
});

// Another listener for same event
emitter.on('orderPlaced', (order) => {
  console.log('📦 Preparing shipment for order:', order.id);
});

// Trigger (emit) the event
emitter.emit('orderPlaced', { id: 123, product: 'Laptop' });

// Output:
// 📧 Sending confirmation email for order: 123
// 📦 Preparing shipment for order: 123

Common Event Methods

Method Description Example
.on(event, fn) Listen for event (multiple times) emitter.on('click', handler)
.once(event, fn) Listen once only emitter.once('connect', handler)
.emit(event, data) Trigger an event emitter.emit('save', data)
.off(event, fn) Remove a listener emitter.off('click', handler)

Practical Example: Order System

// order-events.js
const EventEmitter = require('events');

class OrderSystem extends EventEmitter {
  placeOrder(product, quantity) {
    const order = {
      id: Date.now(),
      product,
      quantity,
      status: 'placed'
    };
    
    console.log('Order placed!', order);
    
    // Emit event - all listeners will be notified
    this.emit('orderPlaced', order);
    
    return order;
  }
}

// Create system
const shop = new OrderSystem();

// Register listeners (like plugins)
shop.on('orderPlaced', (order) => {
  console.log(`📧 Email sent for order #${order.id}`);
});

shop.on('orderPlaced', (order) => {
  console.log(`📊 Analytics updated: ${order.product}`);
});

shop.on('orderPlaced', (order) => {
  console.log(`🏪 Inventory reduced by ${order.quantity}`);
});

// Place an order - all listeners react!
shop.placeOrder('iPhone 15', 2);

Where Node Uses Events

📚 Educational Note: The example below shows how events work internally. In practice, developers use the shorthand version (shown first).
// ✅ NORMAL WAY (what developers actually write)
const http = require('http');

const server = http.createServer((req, res) => {
  res.end('Hello!');
});

server.listen(3000);


// 📚 EQUIVALENT (to show events behind the scenes)
// This is what happens internally:
const http2 = require('http');
const server2 = http2.createServer();

server2.on('request', (req, res) => {
  res.end('Hello!');
});

server2.listen(3001);

// Both do the same thing!
// The callback in createServer() is just a shorthand for .on('request', ...)

4.2 Event Loop (High-Level Overview)

The Event Loop is how Node handles many users with just ONE thread.

┌───────────────────────────────────────────┐ │ Node.js Event Loop │ │ │ User 1 ─────► │ ┌─────────┐ ┌─────────────────────┐ │ User 2 ─────► │ │ Receive │───►│ Start Async Work │ │ User 3 ─────► │ │ Request │ │ (DB, File, Network) │ │ User 4 ─────► │ └─────────┘ └──────────┬──────────┘ │ │ │ │ │ 🔄 Continue to │ │ │ next request │ │ │ ▼ │ │ ┌──────────────────────┐ │ │ │ When done: Callback │ │ │ │ runs and responds │ │ │ └──────────────────────┘ │ └───────────────────────────────────────────┘

Key Points About the Event Loop

1 Single Thread: Node uses only ONE thread for JavaScript
2 Non-Blocking: Slow operations run in background
3 Event Loop: Constantly checks for completed operations
4 Callbacks: When work is done, callback executes

Simple Analogy: Restaurant Waiter

Think of Node.js as a single waiter serving many tables:

  • Takes order from Table 1 → sends to kitchen
  • Doesn't wait! → Takes order from Table 2
  • Takes order from Table 3
  • Kitchen rings bell → Delivers Table 1's food
  • Continues serving other tables...

Result: One waiter can serve many tables efficiently!

Visualizing the Event Loop

// event-loop-demo.js
console.log('1. Script start');

setTimeout(() => {
  console.log('2. Timeout callback');
}, 0);  // Even with 0ms delay!

Promise.resolve().then(() => {
  console.log('3. Promise callback');
});

console.log('4. Script end');

// Output (notice the order!):
// 1. Script start
// 4. Script end
// 3. Promise callback
// 2. Timeout callback
⚠️ Why this order?
  • Synchronous code runs first (1, 4)
  • Promises run next (microtask queue)
  • Timers run last (macrotask queue)
✅ Deterministic Behavior: This output will be exactly the same every time you run it! The event loop order is predictable and consistent. This is a fundamental behavior of JavaScript's event loop.

Why Events Matter for APIs

// Without understanding events, this code is confusing:
const express = require('express');
const app = express();

app.get('/slow', async (req, res) => {
  // This takes 5 seconds...
  await slowDatabaseQuery();
  res.send('Done!');
});

app.get('/fast', (req, res) => {
  res.send('Fast response!');
});

// User A requests /slow (takes 5 seconds)
// User B requests /fast

// ✅ With Event Loop: User B gets response immediately!
// Node doesn't block while waiting for User A's slow query
🎯 Key Takeaways:
  • EventEmitter: Use .on() to listen, .emit() to trigger
  • Event Loop: Node handles many users with one thread
  • Non-blocking: Node continues working while waiting
  • Why it matters: Your API can serve thousands of users efficiently
💡 Remember: You don't need to deeply understand the Event Loop to use Node.js effectively. Just know that:
  • Use async/await for slow operations
  • Node handles concurrency automatically
  • One user's slow request won't block others