Node Events: EventEmitter, Listeners, Errors and Async Event Helpers
How Node's event-based APIs work: EventEmitter and subclassing it, on/once/off/prependListener, why emit() is synchronous, this in listeners, the special "error" event, listener leaks and limits, events.once and events.on for async code, and Node's EventTarget.
kvi5hnuCode Sprout team member6 min readOn this page
Error-first callbacks suit operations that finish once. Many Node objects instead produce a series of happenings of several kinds: a server accepts many connections, a stream delivers data chunk by chunk and then ends, a child process writes output and later exits. These objects are event emitters: instances of EventEmitter from the node:events module, or of its subclasses. Servers, sockets, streams, child processes and process itself are all emitters.
Listening and emitting
Events are identified by name. Register a listener with on(name, fn); trigger the event with emit(name, ...args), which passes the extra arguments to every listener. To build your own event-based API, extend EventEmitter:
const { EventEmitter } = require("node:events");
class Kettle extends EventEmitter {
#temp = 20;
heat(degrees) {
this.#temp = Math.min(100, this.#temp + degrees);
this.emit("temperature", this.#temp);
if (this.#temp === 100) this.emit("boiled", { at: this.#temp });
}
}
const kettle = new Kettle();
kettle.on("temperature", (t) => console.log("display:", t));
kettle.once("boiled", function (info) {
console.log("boiled at", info.at, "| this is the kettle:", this === kettle);
});
kettle.prependListener("temperature", (t) => console.log("logger first:", t));
console.log("before heat");
kettle.heat(50);
kettle.heat(50); // reaches 100: "boiled" fires once
kettle.heat(10); // "boiled" listener was removed by once()
console.log("after heat; emit() is synchronous");
console.log(kettle.listenerCount("temperature"), kettle.listenerCount("boiled"), kettle.eventNames());
before heat
logger first: 70
display: 70
logger first: 100
display: 100
boiled at 100 | this is the kettle: true
logger first: 100
display: 100
after heat; emit() is synchronous
2 0 [ 'temperature' ]
The listener methods:
| Method | Effect |
|---|---|
on(name, fn) / addListener | add a listener at the end of the list |
once(name, fn) | add a listener that removes itself after its first call |
prependListener(name, fn) | add to the front of the list |
off(name, fn) / removeListener | remove a listener; must be the same function reference |
removeAllListeners(name?) | remove all listeners for one event, or for every event |
listenerCount(name), eventNames(), listeners(name) | inspect |
Each registration method returns the emitter, so calls can be chained. Each event's documentation tells you which arguments its listeners receive; a server's connection event, for instance, passes the new socket.
emit() is synchronous

emit() doesn't queue anything. It calls the listeners immediately, one after another, in registration order, and returns only when the last one has returned. In the example, "after heat" printed after all the listener output. Consequences:
- When a Node API emits an event, it waits for your listeners to finish. A slow listener, such as one calling
readFileSyncor doing heavy computation, blocks the whole program, so keep listeners short and move long work elsewhere (article 123). emitreturnstrueif the event had listeners andfalseif not. Return values from listeners are ignored.- Inside a regular
functionlistener,thisis the emitter. Arrow functions keep their outerthisinstead (article 64). - If a listener throws, the exception propagates out of
emit(), and later listeners don't run:
const { EventEmitter } = require("node:events");
const e = new EventEmitter();
e.on("job", () => console.log("handler 1"));
e.on("job", () => { throw new Error("handler 2 failed"); });
e.on("job", () => console.log("handler 3 (never reached)"));
try {
e.emit("job");
} catch (err) {
console.log("emit threw:", err.message);
}
// An "error" event with no listener throws
const conn = new EventEmitter();
try {
conn.emit("error", new Error("connection reset"));
} catch (err) {
console.log("unhandled 'error' event threw:", err.message);
}
// With a listener, it's just an event
conn.on("error", (err) => console.log("handled:", err.message));
conn.emit("error", new Error("connection reset"));
// Removing a listener needs the same function reference
const onTick = () => console.log("tick");
e.on("tick", onTick);
e.off("tick", onTick);
console.log("tick listeners:", e.listenerCount("tick"), "| emit returned", e.emit("tick"));
handler 1
emit threw: handler 2 failed
unhandled 'error' event threw: connection reset
handled: connection reset
tick listeners: 0 | emit returned false
The "error" event
Event-based APIs report failures with an event named "error", the counterpart of the error argument in callbacks. This event gets special treatment: if "error" is emitted and no listener is registered, emit throws the error. Since network and stream errors happen asynchronously, nobody can catch that exception, and the process crashes.
The rule is simple: always add an "error" listener to sockets, streams, servers, child processes and your own emitters. For example, a server that fails to listen because the port is taken emits error with code EADDRINUSE, which you can handle by reporting it clearly instead of crashing with a stack trace.
The example also shows a classic bug: off with a different function, such as a fresh arrow function, removes nothing. Keep a reference to any listener you plan to remove.
Listener leaks
Adding a listener every time something happens, for example inside a request handler on a long-lived emitter, makes the list grow without bound: a memory leak, and every emit gets slower. To catch this, Node prints a MaxListenersExceededWarning when one event gets more than 10 listeners. The limit doesn't stop anything; it's only a warning. If an emitter legitimately needs more, raise its limit:
const { EventEmitter } = require("node:events");
const bus = new EventEmitter();
console.log("default limit:", bus.getMaxListeners());
bus.setMaxListeners(50); // this emitter legitimately has many listeners
for (let i = 0; i < 20; i++) bus.on("message", () => {});
console.log("listeners:", bus.listenerCount("message"), "(no warning)");
bus.removeAllListeners("message");
console.log("after removeAllListeners:", bus.listenerCount("message"));
// EventTarget, the browser-style API, also exists in Node
const target = new EventTarget();
target.addEventListener("ping", (event) => console.log("EventTarget got", event.type, event.detail), { once: true });
target.dispatchEvent(new CustomEvent("ping", { detail: 42 }));
target.dispatchEvent(new CustomEvent("ping", { detail: 43 })); // listener already removed
default limit: 10
listeners: 20 (no warning)
after removeAllListeners: 0
EventTarget got ping 42
Node also implements the web-standard EventTarget and Event classes (article 108), with addEventListener and dispatchEvent, mainly for web-compatible APIs such as AbortSignal and BroadcastChannel. Most Node core modules use EventEmitter.
Events with promises and async iteration
The node:events module has two helpers that connect events to async code (articles 98 and 99):
events.once(emitter, name, options?)returns a promise that resolves with the next event's arguments as an array. It rejects if the emitter emits"error"first, and it accepts anAbortSignalso you can stop waiting.events.on(emitter, name, options?)returns an async iterator over every future event, for use withfor await. Pass asignal(or, in recent versions, acloseoption naming an ending event) so the loop can finish.
const { EventEmitter, once, on } = require("node:events");
const queue = new EventEmitter();
async function main() {
// once() returns a promise for the next event's arguments
setTimeout(() => queue.emit("ready", "db", 3), 5);
const [name, tries] = await once(queue, "ready");
console.log("ready:", name, tries);
// An AbortSignal times out the wait
const timeout = new AbortController();
setTimeout(() => timeout.abort(), 20);
try {
await once(queue, "never", { signal: timeout.signal });
} catch (err) {
console.log("gave up waiting:", err.name);
}
// on() turns events into an async iterator
setTimeout(() => {
for (const n of [1, 2, 3]) queue.emit("order", { id: n });
queue.emit("closed");
}, 5);
const ac = new AbortController();
queue.once("closed", () => ac.abort());
try {
for await (const [order] of on(queue, "order", { signal: ac.signal })) {
console.log("order", order.id);
}
} catch (err) {
console.log("loop ended:", err.name);
}
}
main();
ready: db 3
gave up waiting: AbortError
order 1
order 2
order 3
loop ended: AbortError
Together with node:timers/promises, these let you write code like await once(server, "listening") in tests and startup sequences instead of nesting callbacks.
Common questions
Are EventEmitter listeners called asynchronously?
No. emit() calls them synchronously, in order, before it returns. If you need a listener's work to happen later, schedule it inside the listener with setImmediate, queueMicrotask or a promise.
Why did my process crash with "Unhandled 'error' event"?
An emitter, often a socket, stream or child process, emitted "error" and nothing was listening. Add emitter.on("error", handler) to every emitter that can fail.
Should I raise the max listeners limit when I see the warning?
First check for a leak: are you adding listeners repeatedly without removing them? Raise the limit with setMaxListeners only when many listeners are intentional.
Summary
- Objects that produce multiple kinds of events extend
EventEmitter. Register listeners withon,onceorprependListener; remove them withoff, using the same function reference. emit(name, ...args)calls listeners synchronously, in order, withthisset to the emitter; a throwing listener stops the rest and the exception propagates out ofemit.- Always listen for
"error": emitting it with no listener throws and usually crashes the process. - More than 10 listeners for one event triggers a leak warning; fix leaks, or use
setMaxListenerswhen it's intentional. events.oncegives a promise for the next event;events.ongives an async iterator of events.
Practice Questions
What does this print?
const { EventEmitter } = require("node:events");
const e = new EventEmitter();
e.on("go", () => console.log("A"));
console.log("before");
e.emit("go");
console.log("after");
Answer
before, A, after. emit runs the listener synchronously before returning.
This code never removes the listener. Why?
socket.on("data", (chunk) => handle(chunk));
// later
socket.off("data", (chunk) => handle(chunk));
Answer
The second arrow function is a new function object, not the one that was registered, so off finds nothing to remove. Instead, store the listener in a variable and pass that same variable to both on and off.
How can an async function pause until an HTTP server has started listening?
Answer
const { once } = require("node:events");
server.listen(0);
await once(server, "listening");
console.log("port", server.address().port);
If the server emits "error" first (for example EADDRINUSE), the promise rejects.
Write a Timer class that emits "tick" with a counter every 100 ms and "done" after a given number of ticks.
Answer
const { EventEmitter } = require("node:events");
class Timer extends EventEmitter {
start(ticks) {
let count = 0;
const id = setInterval(() => {
this.emit("tick", ++count);
if (count === ticks) {
clearInterval(id);
this.emit("done");
}
}, 100);
return this;
}
}
new Timer().on("tick", (n) => console.log(n)).on("done", () => console.log("done")).start(3);
Arrow functions inside start keep this pointing at the timer.
Previous: Node Buffers: Binary Data, Encodings, Reading and Writing Bytes
Next: Node Streams: Readable, Writable, Duplex and Transform, Pipelines and Async Iteration

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.