Events Module
EventEmitter, listeners, once, and event-driven design.
Node is event-driven to its core
Much of Node's standard library is built on one pattern: an object emits named events, and interested code registers listeners for them. HTTP servers emit request, streams emit data and end, process emits exit. The class behind all of this is EventEmitter from the events module.
The pattern decouples code beautifully: the emitter doesn't know or care who is listening. One event can have zero, one, or many listeners — each part of your app reacts independently.
const EventEmitter = require("events");
const emitter = new EventEmitter();
// Register a listener for the "greet" event:
emitter.on("greet", (name) => {
console.log("Hello, " + name + "!");
});
// Emit it - arguments after the name go to listeners:
emitter.emit("greet", "Ada");
emitter.emit("greet", "Grace");on, once, off
The three listener-management methods:
on(event, fn)— runfnevery time the event fires (alias:addListener)once(event, fn)— runfnfor the first occurrence only, then auto-remove itoff(event, fn)— remove a listener (alias:removeListener); you must pass the same function reference you registered
Listeners run synchronously, in registration order, when emit is called. emit returns true if at least one listener handled the event.
const EventEmitter = require("events");
const emitter = new EventEmitter();
const always = () => console.log("every time");
emitter.on("ping", always);
emitter.once("ping", () => console.log("first time only"));
emitter.emit("ping"); // both listeners run
emitter.emit("ping"); // only "every time"
emitter.off("ping", always); // must be the same reference
console.log("handled?", emitter.emit("ping")); // false - no listeners leftBuilding your own emitters
Real applications subclass EventEmitter to give domain objects event capabilities. An order processor might emit paid and shipped; a job queue might emit done and failed. Consumers subscribe to what they care about — logging, notifications, and metrics stay separate from the core logic.
This is the observer pattern: the subject broadcasts, observers react, neither depends on the other's internals.
const EventEmitter = require("events");
class OrderProcessor extends EventEmitter {
process(order) {
this.emit("started", order.id);
// ...imagine payment logic here...
this.emit("paid", order.id, order.total);
this.emit("shipped", order.id);
}
}
const processor = new OrderProcessor();
processor.on("paid", (id, total) =>
console.log("[billing] order " + id + " paid $" + total));
processor.on("shipped", (id) =>
console.log("[email] order " + id + " is on its way"));
processor.process({ id: "A42", total: 99 });The special 'error' event
One event name is magic: `error`. If an emitter emits "error" and no listener is registered for it, Node throws the error — usually crashing the process. This is deliberate: unhandled failures should be loud, not silent.
Rule: any emitter that might emit error (streams, sockets, servers...) should have an error listener attached. It is the emitter-world equivalent of a try/catch.
const EventEmitter = require("events");
const safe = new EventEmitter();
safe.on("error", (err) => {
console.log("Caught gracefully:", err.message);
});
safe.emit("error", new Error("disk on fire"));
console.log("Still alive!");
// Without that listener, the emit line would THROW
// and crash the program.Listener hygiene
A few practical details keep event code healthy:
listenerCount(event)andeventNames()— inspect what's registeredremoveAllListeners(event)— bulk cleanup (useful in tests)- Node warns if one event collects more than 10 listeners — usually a sign of a leak where listeners are added repeatedly (in a loop or per-request) but never removed. Raise the limit with
setMaxListeners(n)only when the count is genuinely intentional. - Prefer
oncefor one-shot events so cleanup is automatic
const EventEmitter = require("events");
const emitter = new EventEmitter();
emitter.on("data", () => {});
emitter.on("data", () => {});
emitter.once("end", () => {});
console.log("events:", emitter.eventNames()); // [ 'data', 'end' ]
console.log("data listeners:", emitter.listenerCount("data")); // 2
emitter.removeAllListeners("data");
console.log("after cleanup:", emitter.listenerCount("data")); // 0Check your understanding
5 questionsQuestion 1 of 5
Score: 0