Events and EventEmitter

Topic 3 of 5 in The Node runtime6 min readIntermediateFree course

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.

An orders emitter calls emit(‘placed’, order). Three listeners receive it: one sends an email, one updates stock, and a once listener logs the first sale. Listeners run synchronously in the order they were added, and the emitter doesn’t know who is listening.

The basics

JavaScript
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) — call listener every 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.

JavaScript
bus.on('ping', () => console.log('listener'));

console.log('before');
bus.emit('ping');
console.log('after');
// before, listener, after

So 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:

JavaScript
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.

JavaScript
const emitter = new EventEmitter();
emitter.emit('error', new Error('Something broke')); // crashes: Unhandled 'error' event

So whenever you use an emitter that might fail — streams, sockets, servers, child processes — attach an error listener:

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
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.

Exercise

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.

JavaScript
import { EventEmitter } from 'node:events';

class OrderService extends EventEmitter {
  // your code here
}

Summary

  • An EventEmitter lets one part of a program announce things without knowing who is listening.
  • on adds a listener, once listens a single time, off removes one, emit triggers 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.