Events and EventEmitter
Overview
Much of Node.js is built on one simple pattern: an object emits named events, and other code listens for them. An HTTP server emits 'request' for every incoming request. A file stream emits 'data' for every chunk and 'end' when it’s done. A child process emits 'exit'.
The class behind all of these is EventEmitter, from node:events. Once you understand it, a large part of Node’s API suddenly looks familiar.
The basics
import { EventEmitter } from 'node:events';
const bus = new EventEmitter();
bus.on('user:registered', (user) => {
console.log(`Send welcome email to ${user.email}`);
});
bus.on('user:registered', (user) => {
console.log(`Add ${user.email} to the newsletter`);
});
bus.emit('user:registered', { email: 'asha@example.com' });on(name, listener)— calllistenerevery time the event happens.emit(name, ...args)— trigger the event, passing any arguments to each listener.once(name, listener)— listen for the next occurrence only.off(name, listener)— remove a listener (pass the same function you added).
Event names are just strings. A noun:verb style such as 'order:placed' keeps them organised.
Why use events?
Events decouple code. The registration code doesn’t need to know about email, newsletters, analytics or anything else that should happen when someone signs up — it just announces the fact. New behaviour can be added by adding a listener, without touching the code that emits.
That’s also the downside: when there are many listeners in many files, it can be hard to see what happens when an event fires. Use events where independence is valuable, and plain function calls where the steps are part of one clear process.
Listeners run synchronously
This surprises many people: emit calls each listener immediately, one after another, and only returns when they’ve all finished.
bus.on('ping', () => console.log('listener'));
console.log('before');
bus.emit('ping');
console.log('after');
// before, listener, afterSo a slow listener slows down the code that emitted. If a listener needs to do async work, it can start it (it’s fine for a listener to be an async function), but emit won’t wait for it — and any rejection must be handled inside the listener.
Building your own emitter
Extend EventEmitter to give your own classes events:
import { EventEmitter } from 'node:events';
class Downloader extends EventEmitter {
async download(urls) {
for (const [i, url] of urls.entries()) {
const res = await fetch(url);
this.emit('progress', { done: i + 1, total: urls.length, url });
}
this.emit('finished');
}
}
const dl = new Downloader();
dl.on('progress', ({ done, total }) => console.log(`${done}/${total}`));
dl.once('finished', () => console.log('All done'));
await dl.download(['https://example.com', 'https://example.org']);The ‘error’ event
'error' is special. If an emitter emits 'error' and nothing is listening, Node throws the error — which, if uncaught, crashes the whole process.
const emitter = new EventEmitter();
emitter.emit('error', new Error('Something broke')); // crashes: Unhandled 'error' eventSo whenever you use an emitter that might fail — streams, sockets, servers, child processes — attach an error listener:
stream.on('error', (err) => {
console.error('Stream failed:', err.message);
});Awaiting events
The once function (not the method) returns a promise that resolves the next time an event fires — and rejects if 'error' fires first:
import { once } from 'node:events';
server.listen(3000);
await once(server, 'listening');
console.log('Server is ready');And on (the function) gives you an async iterator, so you can handle a stream of events with for await:
import { on } from 'node:events';
for await (const [order] of on(orders, 'placed')) {
console.log('New order', order.id);
}Memory-leak warnings
If more than 10 listeners are added for the same event, Node prints a MaxListenersExceededWarning. It’s usually a sign of a bug — for example, adding a listener inside a function that runs on every request, so listeners pile up forever:
app.get('/stats', (req, res) => {
bus.on('update', () => {}); // ✗ a new listener on every request!
});Add listeners once, during setup, and remove them (off) when the thing they belong to goes away. If you genuinely need many listeners, raise the limit with emitter.setMaxListeners(n).
EventTarget
Node also supports the browser’s EventTarget and Event classes, which some newer APIs (like AbortSignal) use. The ideas are the same; EventEmitter is still what you’ll meet in most Node code.
Where you’ll see it next: streams, HTTP servers, WebSockets and child processes are all EventEmitters. Every
.on('data'),.on('close')and.on('error')you write from now on is this pattern.
An order emitter
Create an OrderService class that extends EventEmitter. Its place(order) method should save the order to an array and emit 'placed' with the order. Add two listeners: one that logs an email confirmation, one that counts total revenue. Handle 'error' too.
import { EventEmitter } from 'node:events';
class OrderService extends EventEmitter {
// your code here
}import { EventEmitter } from 'node:events';
class OrderService extends EventEmitter {
#orders = [];
place(order) {
if (!order.total || order.total <= 0) {
this.emit('error', new Error('Order total must be positive'));
return;
}
this.#orders.push(order);
this.emit('placed', order);
}
}
const orders = new OrderService();
let revenue = 0;
orders.on('placed', (o) => console.log(`Email: thanks for order ${o.id}`));
orders.on('placed', (o) => { revenue += o.total; });
orders.on('error', (err) => console.error('Order failed:', err.message));
orders.place({ id: 1, total: 499 });
orders.place({ id: 2, total: 0 });
console.log({ revenue }); // { revenue: 499 }Summary
- An EventEmitter lets one part of a program announce things without knowing who is listening.
onadds a listener,oncelistens a single time,offremoves one,emittriggers them.- Listeners run synchronously, in the order they were added.
- Always listen for
'error'— an unhandled'error'event crashes the process. - Streams, servers, sockets and child processes are all EventEmitters.