Node.js theorytheory 0/50 · 0%
Patterns · easy

13. EventEmitter

The pub/sub pattern underlying most of Node's core APIs.

`EventEmitter` is the base class behind streams, servers, and many other Node objects. You register listeners with `.on(event, handler)` and fire them with `.emit(event, ...args)`.

js
import { EventEmitter } from "node:events";

class Wallet extends EventEmitter {
  deposit(amount) {
    this.balance = (this.balance ?? 0) + amount;
    this.emit("deposit", amount, this.balance);
  }
}

const w = new Wallet();
w.on("deposit", (amount, balance) => console.log(`+${amount}, now ${balance}`));
w.deposit(10);

By convention, an `"error"` event with no listener attached throws and crashes the process — always attach an `"error"` handler on emitters that might fail, such as sockets and streams.

Check your understanding

  1. 1. What happens if an EventEmitter emits 'error' with no listener?

  2. 2. Which core Node classes are built on EventEmitter?

  3. 3. How do you register a listener?