Events and EventEmitter

Beginner · 8 min

The observer pattern in Node with on, once and emit, the error event, the max-listeners leak warning, events.once, events.on and EventTarget.

Before thisThe event loop phases

Codevolution · 8 min

Events and EventEmitter

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • An `EventEmitter` lets code announce that something happened (`emit`) without knowing who is listening (`on`). Streams, HTTP servers, child processes and `process` itself are all emitters.
  • `emit` calls the listeners synchronously, in the order they were added, before `emit` returns. A throwing listener stops the later ones, and the exception reaches the caller of `emit`.
  • An event named `'error'` is special: emitting it with no listener throws the error and can crash the process. Always attach an `'error'` listener to emitters that can fail.
  • More than 10 listeners for one event triggers `MaxListenersExceededWarning`. It almost always means listeners are added repeatedly and never removed, which is a memory leak.
  • `await events.once(emitter, 'name')` turns the next event into a promise, and `events.on` into an async iterator. Both reject if the emitter emits `'error'`, and both accept an `AbortSignal`.

The problem: announcing without knowing who is listening

A download finishes. The progress bar wants to know, the logger wants to know, and the cache wants to know. If the downloader calls each of them by name, it depends on all of them, and adding a fourth listener means editing the downloader. The fix is the observer pattern: the downloader says “done” to anyone who has asked to hear it, and does not care who that is.

Node’s version is EventEmitter from node:events, and a surprising amount of Node is built on it: http.Server, net.Socket, streams, child_process, and the global process. Learning it once pays off everywhere.

import { EventEmitter } from 'node:events';

const bus = new EventEmitter();
bus.on('msg', (a, b) => console.log('on', a, b));
bus.once('msg', () => console.log('once (runs one time)'));

bus.emit('msg', 1, 2);   // on 1 2 / once (runs one time)
bus.emit('msg', 3, 4);   // on 3 4
bus.emit('nobody');      // returns false: no listeners

on registers a listener for the event name. once registers one that removes itself after the first call. emit(name, ...args) calls every listener with those arguments and returns true if there was at least one. off (or removeListener) removes a listener, and you need the same function reference you registered, so named functions help.

Emit is synchronous

This is the part people get wrong. emit does not schedule anything. It loops over the listeners and calls each one, right now:

bus.on('tick', () => console.log('listener'));
console.log('before');
bus.emit('tick');
console.log('after');
// before, listener, after

Three consequences. Listeners run in the order they were added (use prependListener to go first). A listener that throws stops the remaining ones and the exception propagates out of emit to whoever called it; in a test, the second listener never ran. And a slow listener blocks the emitter and the caller, which is a blocking problem like any other. If you want deferred delivery, do it explicitly with queueMicrotask or setImmediate inside the listener. Likewise, async listeners are not awaited: emit does not wait for the promises they return. If one rejects, it becomes an unhandled rejection, unless you create the emitter with { captureRejections: true }, which routes the rejection to the 'error' event.

Regular function listeners get the emitter as this. Arrow functions do not, since they keep the surrounding this.

Extending EventEmitter

The usual way to use it is to give a class the ability to emit:

class Job extends EventEmitter {
  run() {
    this.emit('start');
    queueMicrotask(() => this.emit('done', 42));
  }
}
const j = new Job();
j.on('start', () => console.log('start'));
j.on('done', (r) => console.log('done', r));
j.run();     // start, done 42

The caller subscribes first, then triggers work. If the work emitted synchronously inside the constructor, no one would have had time to subscribe, which is why constructors that emit are a trap.

The special ‘error’ event

One event name has rules. If you emit('error', err) and there is no listener for 'error', Node throws err out of the emit call:

try { bus.emit('error', new Error('boom')); } catch (e) { console.log('thrown:', e.message); }
bus.on('error', (e) => console.log('handled:', e.message));
bus.emit('error', new Error('boom2'));   // handled: boom2

Without the try, that throw inside an I/O callback is an uncaught exception and the process exits. The design is deliberate: an unhandled failure should not be silent. So whenever you create or receive an emitter that can fail, such as a stream, a socket or a child process, attach an 'error' listener. See handling uncaught errors and rejections for the process-level view.

The leak warning

for (let i = 0; i < 11; i++) leaky.on('x', () => {});

On the eleventh listener Node prints MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 x listeners added. The default limit of 10 is a heuristic. A healthy program rarely has more than a handful of listeners for one event on one emitter. A growing count means something adds a listener per request or per iteration and never removes it. Each listener keeps its closure alive, so memory climbs. The fix is to remove them (off, once, or events.on with an AbortSignal), or to reuse one listener. emitter.getMaxListeners() and setMaxListeners(n) exist for the rare case where many listeners is intended. events.getEventListeners(emitter, 'x') shows what is attached, a useful tool for memory leaks and heap snapshots.

Events as promises and iterators

Since callbacks and promises mix poorly, node:events offers two bridges:

import { once, on } from 'node:events';

const [value] = await once(emitter, 'ready');        // resolves with the arguments array

for await (const [n] of on(emitter, 'data')) {        // async iterator over every 'data' event
  if (n === 3) break;
}

once rejects if the emitter emits 'error' first, which gives you normal try/catch flow. Both accept { signal } to cancel waiting; an aborted once rejects with an AbortError. This is also how the stream and HTTP APIs let you await things, and connects to cancellation with AbortController.

EventTarget

Node also has the browser’s EventTarget and Event classes, global and standard:

const et = new EventTarget();
et.addEventListener('ping', (e) => console.log(e.type), { once: true });
et.dispatchEvent(new Event('ping'));

AbortSignal is an EventTarget. Prefer EventTarget when you write code that should also run in browsers, and EventEmitter for Node-only code that needs 'error' semantics, once helpers or Node’s stream ecosystem.

What the video covers

Codevolution’s eight-minute video introduces the events module: creating an emitter, registering listeners with on, and triggering them with emit, with arguments. The error event, the leak warning, events.once and events.on, captureRejections and EventTarget come from the prose, each run against Node 26.13.1. The video is from December 2022, and the basics have not changed. No transcript was available. Mosh’s 2018 video under “go deeper” is a similar introduction.

Where this fits

Emitters are the substrate for streams and the HTTP server. The next lesson covers the data those streams carry: buffers and binary data. If you know browser events, DOM manipulation and events shows the same idea in the page.

Check yourself

  1. 01Given `bus.on('tick', () => console.log('listener'))`, what does `console.log('before'); bus.emit('tick'); console.log('after');` print?

    `before`, `listener`, `after`. `emit` runs listeners synchronously before it returns. An emitter is not a queue and does nothing asynchronous by itself.

  2. 02What happens when you call `emitter.emit('error', new Error('boom'))` and nothing has listened for `'error'`?

    The error is thrown from the `emit` call. Inside a callback with nothing to catch it, that becomes an uncaught exception that terminates the process. Adding `emitter.on('error', handler)` makes it an ordinary event.

  3. 03You see `MaxListenersExceededWarning: 11 x data listeners added`. What does the warning mean, and is raising the limit the right fix?

    It is a heuristic that listeners are being added in a loop or per request and never removed, so the list and everything it captures grows without bound. First find and remove the leak with `off`, `once`, or an `AbortSignal`. Raise the limit with `setMaxListeners` only if you really need that many.

  4. 04Why does `await once(emitter, 'ready')` return an array?

    An event can carry several arguments, and a promise resolves with one value. `once` resolves with the arguments array, so `const [value] = await once(emitter, 'ready')` unpacks the first one.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark