Tell me when it happens
Servers emit request, streams emit data and end, processes emit exit. They're all built on one class: EventEmitter — objects that announce things, and listeners that react.
on, once, emit
import { EventEmitter } from "node:events";
class Kitchen extends EventEmitter {
order(dish) {
this.emit("order", dish);
setTimeout(() => this.emit("ready", dish), 50);
}
}
const kitchen = new Kitchen();
kitchen.on("order", (dish) => console.log("Cooking", dish));
kitchen.on("ready", (dish) => console.log(dish, "is ready!"));
kitchen.once("ready", () => console.log("(first dish out)"));
kitchen.order("Momo");
kitchen.order("Thukpa");- Emit an error event with no listener and Node throws — always handle error on emitters.
- emitter.off(name, fn) removes a listener; forgetting to is a classic memory leak.
- Streams (fs.createReadStream, HTTP requests) are EventEmitters that deliver data in chunks.