Node.js Events
Much of Node is built around events: a server emits "request" when a client connects, a stream emits "data" when a chunk arrives, a process emits "exit" before it stops. The machinery behind all of these is one class from the node:events module: EventEmitter.
The pattern is simple: some code listens for a named event with on(), and other code emits that event with emit(), optionally passing data.
Your first EventEmitter
const EventEmitter = require("node:events");
const door = new EventEmitter();
door.on("open", (who) => {
console.log(`${who} opened the door`);
});
door.on("open", () => {
console.log("Ding-dong!");
});
door.emit("open", "Alice");
door.emit("open", "Bob");
console.log("listeners for open:", door.listenerCount("open"));Alice opened the door
Ding-dong!
Bob opened the door
Ding-dong!
listeners for open: 2
Listeners run synchronously, in the order they were added, at the moment emit() is called. emit() returns true if anyone was listening.
The main methods
| Method | What it does |
|---|---|
on(name, fn) / addListener |
run fn every time the event fires |
once(name, fn) |
run fn only the first time, then remove it |
off(name, fn) / removeListener |
remove a specific listener |
removeAllListeners([name]) |
remove all listeners (for one event or all) |
emit(name, ...args) |
call every listener with the arguments |
listenerCount(name) |
how many listeners are attached |
prependListener(name, fn) |
add a listener to the front of the queue |
setMaxListeners(n) |
change the leak-warning threshold (default 10) |
once and off
const { EventEmitter } = require("node:events");
const app = new EventEmitter();
app.once("ready", () => console.log("ready! (only once)"));
function logTick(n) { console.log("tick", n); }
app.on("tick", logTick);
app.emit("ready");
app.emit("ready"); // nobody listens any more
app.emit("tick", 1);
app.emit("tick", 2);
app.off("tick", logTick);
console.log("emit returned:", app.emit("tick", 3));ready! (only once)
tick 1
tick 2
emit returned: false
Tip: To remove a listener you need a reference to the same function. Inline arrow functions can't be removed with
off, so name the function if you plan to detach it.
Extending EventEmitter
The idiomatic way to use events is to make your own class that extends EventEmitter. Here a tiny order queue notifies listeners about its progress:
import { EventEmitter } from "node:events";
class OrderQueue extends EventEmitter {
#orders = [];
add(item) {
this.#orders.push(item);
this.emit("added", item, this.#orders.length);
}
processAll() {
while (this.#orders.length > 0) {
const item = this.#orders.shift();
this.emit("processed", item);
}
this.emit("empty");
}
}
const queue = new OrderQueue();
queue.on("added", (item, size) => console.log(`+ ${item} (queue size ${size})`));
queue.on("processed", (item) => console.log(`✔ shipped ${item}`));
queue.on("empty", () => console.log("all orders shipped"));
queue.add("book");
queue.add("lamp");
queue.processAll();+ book (queue size 1)
+ lamp (queue size 2)
✔ shipped book
✔ shipped lamp
all orders shipped
The special error event
If an emitter emits "error" and no error listener is attached, Node throws the error and — unless something catches it — crashes the process. Always listen for error on emitters that can fail (streams, servers, sockets).
const { EventEmitter } = require("node:events");
const job = new EventEmitter();
try {
job.emit("error", new Error("disk full"));
} catch (err) {
console.log("thrown because nobody listened:", err.message);
}
job.on("error", (err) => console.log("handled:", err.message));
job.emit("error", new Error("disk full"));thrown because nobody listened: disk full
handled: disk full
Waiting for an event with await
events.once() (the module-level function, not the method) returns a promise that resolves with the event's arguments — perfect for async code:
import { EventEmitter, once } from "node:events";
const download = new EventEmitter();
setTimeout(() => download.emit("done", "report.pdf", 2048), 10);
console.log("waiting for download...");
const [file, bytes] = await once(download, "done");
console.log(`got ${file} (${bytes} bytes)`);waiting for download...
got report.pdf (2048 bytes)
Note: Browser code uses a similar but separate API,
EventTargetwithaddEventListener. Node supportsEventTargettoo, but most Node APIs areEventEmitters.
Test yourself
When do listeners run after emitter.emit('x') is called?
- On the next tick of the event loop
- Immediately and synchronously, in the order they were added
- In random order
- Only after a timer
What happens if you emit 'error' with no error listener attached?
- Nothing
- A warning is printed
- The error is thrown
- The event is queued until a listener is added
Which method attaches a listener that fires at most one time?
onsingleonceprependListener