Lesson 13 / 28
The EventEmitter Pattern
The publish/subscribe pattern that much of Node's core is built on.
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.