Lesson 13 / 30
The EventEmitter Pattern
Use the EventEmitter publish-subscribe pattern that powers streams, HTTP servers and much of Node's core.
emit and on
Create an emitter, subscribe with on, fire an event with emit.
import { EventEmitter } from "node:events";
const orders = new EventEmitter();
orders.on("placed", (item) => {
console.log(`Order received: ${item}`);
});
orders.emit("placed", "Laptop");
Output:
Order received: Laptop
A radio station
An EventEmitter is like a radio station: it broadcasts (emit), and any number of listeners can tune in (on) without the station knowing who they are.
Core Node runs on it
HTTP servers, streams, and process itself are all EventEmitters under the hood — request, data, close are all events.