Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 133 ยท The Runtime

Events and EventEmitter

Learn Node.js events - EventEmitter on, once, off and emit, listener order, the special error event, events.once and on, captureRejections, EventTarget and memory leak warnings.

A great deal of Node.js is built on one simple idea: an object announces that something happened, and any code that cares can react. A server announces each incoming request. A stream announces each chunk of data and its end. A child process announces that it exited. The announcing is called emitting an event, the reacting code is a listener, and the class that makes it all work is EventEmitter.

You will use EventEmitter directly when you build your own components, and indirectly every time you call server.on('request', ...) or stream.on('data', ...). This lesson covers the API from the first on call to the traps that catch experienced developers: the special error event, listener leaks, this in listeners, and mixing promises with events. It pairs naturally with The Event Loop and Streams Fundamentals.

The basics: on, emit, once, off

Create an emitter, register listeners with on(eventName, listener), and trigger them with emit(eventName, ...args). Every argument after the event name is passed to each listener.

Node.js Registering listeners and emitting events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Four things to observe:

  • Listeners run in the order they were registered, one after the other.
  • once registers a listener that removes itself after its first call.
  • emit returns true if at least one listener ran and false otherwise.
  • Emitting an event nobody listens to is not an error (with one exception, coming up).

To remove a listener, call off(eventName, listener) (alias removeListener) with the same function you registered. This is why inline arrow functions are awkward to remove; keep a reference when you will need to. removeAllListeners(eventName) clears everything for one event, and listenerCount, listeners and eventNames let you inspect the current state.

Emitting is synchronous

emit does not queue anything. It calls every listener, right now, in the same call stack, and returns only after they have all finished. A slow listener slows the code that emitted; a listener that throws throws into the emitter's caller.

Node.js emit runs listeners immediately, in order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If you need listeners to run asynchronously, wrap the work yourself with setImmediate or queueMicrotask inside the listener, or await something. An emitter never does it for you.

Building your own emitter

The usual way to use EventEmitter is to extend it, so your class gains on, emit and the rest. Call super() first in the constructor. Name events with simple strings ('progress', 'done'), document their arguments like any other API, and prefer a small fixed vocabulary.

Node.js A class that emits progress events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice this inside the function listener. Node calls listeners with this set to the emitter. If you use an arrow function instead, this is whatever it was where the arrow was written, so arrows are the better choice when you want the surrounding object (for instance, inside another class's method).

The special error event

One event name has special rules: 'error'. If you emit 'error' and no listener is registered for it, Node does not shrug and return false. It throws the error you passed. If the emitted value is not an Error, it throws a wrapper error with code ERR_UNHANDLED_ERROR. Inside an event callback this typically becomes an uncaught exception, which ends the process.

Node.js Emitting error with no listener (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The program prints got 1, and then crashes with the stack trace of Error: disk on fire, followed by an extra block starting Emitted 'error' event at: that points at the emit call. Exit code 1.

The rule: every emitter that can fail needs an 'error' listener. Streams, sockets, servers and child processes are all emitters, and an unhandled 'error' on any of them takes the whole process down. Add the listener at creation time.

Node.js Handling the error event

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Always emit real Error objects, never strings, so stack traces and error.code survive. More on error design in Errors and Error Handling.

Waiting for events with promises

Callback-style listeners do not combine well with async/await. The events module provides two helpers to bridge that gap.

events.once(emitter, name) returns a promise that resolves with an array of the event's arguments the first time the event fires. If the emitter emits 'error' while you wait, the promise rejects with it, so you get ordinary try/catch. events.on(emitter, name) returns an async iterator yielding an array of arguments for every emission, which you consume with for await. Pass an AbortSignal to stop it.

Node.js events.once and events.on

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

When the iterator is aborted it throws an AbortError, which is how a for await over events normally ends. Messages emitted while your loop body is busy are buffered, so none are lost. Compare this with async iterators in the asynchronous-programming chapter.

Do not pass an async function as a listener unless you understand what happens to its rejection. An exception thrown inside an async listener does not reach the emitter; it becomes an unhandled promise rejection.

captureRejections

Create an emitter with { captureRejections: true } and Node attaches a catch to every promise returned by a listener. A rejection is routed to the 'error' event instead of being lost.

Node.js Async listeners and captureRejections

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Without captureRejections the failure went to the global unhandledRejection handler (which in a real program without that handler would crash Node). With it, the failure arrives where you expect it. The setting is per emitter; classes that extend EventEmitter can pass it to super({ captureRejections: true }).

Too many listeners: the memory leak warning

A listener holds on to everything its function closes over. Adding listeners repeatedly without removing them, for example inside a request handler to an emitter that lives for the whole program, leaks memory. Node watches for the most common version of this mistake: more than 10 listeners for one event on one emitter prints a MaxListenersExceededWarning.

Node.js The leak warning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The warning names the event, the count and the limit. It is only a warning; the listeners are still added. If the number is genuinely intended (a hub with dozens of subscribers) call emitter.setMaxListeners(n), or setMaxListeners(0) for unlimited. If it is not intended, find the code that registers listeners in a loop and remove them with off, use once, or switch to events.once and events.on, which accept an AbortSignal and clean up after themselves.

Handy listener tools

  • emitter.on('newListener', fn) fires before a listener is added, and 'removeListener' after one is removed. They are used by libraries that start expensive work only when somebody subscribes.
  • emitter.rawListeners(name) returns the listeners including once wrappers; emitter.listeners(name) returns the original functions.
  • emitter.eventNames() lists the events that currently have listeners. Event names can also be Symbols, which avoids collisions in libraries.
  • events.getEventListeners(target, name) works on both EventEmitter and EventTarget.

EventTarget: the browser's way

Browsers do not have EventEmitter; they use EventTarget and Event. Node implements those too, as globals, and many newer APIs (AbortSignal, fetch internals, MessagePort) are EventTargets. The differences are mostly API shape:

EventEmitter EventTarget
Register on(name, fn) addEventListener(name, fn, options)
Remove off(name, fn) removeEventListener(name, fn)
Trigger emit(name, ...args) dispatchEvent(new Event(name))
Arguments any number a single Event object (data in detail for CustomEvent)
error special rule yes no
One-time listener once { once: true } option
Node.js The same idea with EventTarget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For code that must run in both Node and browsers, EventTarget is the portable choice (see Node.js vs the Browser). Inside Node-only code, EventEmitter is more flexible and faster. Note that an error thrown in an EventTarget listener does not reach dispatchEvent's caller; Node reports it as an uncaught exception on a later tick.

Design advice

  • Emit past tense for facts ('connected', 'closed') and imperative for requests ('retry'), and keep the set of event names small and documented.
  • Prefer a single object argument when events carry more than two or three values, so adding a field later does not break listeners.
  • Do not use events where a promise fits. If something happens exactly once and has a result, return a promise. Use events for things that can happen zero, one or many times.
  • Do not rely on listener order across unrelated modules. It depends on registration order, which can change.
  • Clean up. Every on should have a story for when the matching off happens.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does emitter.emit('x', 1, 2) do?

    emit is synchronous: listeners run in registration order, in the caller's stack, and emit returns a boolean.
  2. 2. What happens when you emit 'error' on an EventEmitter that has no 'error' listener?

    'error' is special: with no listener the emitted error is thrown. Always attach an error listener to emitters that can fail.
  3. 3. What does await once(emitter, 'ready') resolve with?

    once resolves with an array of the event's arguments, so you usually destructure it. It rejects if 'error' is emitted first.
  4. 4. A listener is written as an async function and throws. With a default EventEmitter, where does the failure go?

    The listener's returned promise rejects and nobody awaits it. captureRejections: true would route it to the 'error' event instead.
  5. 5. What does the MaxListenersExceededWarning tell you?

    It is a warning only; more than 10 listeners for one event is a common sign of listeners being added repeatedly without removal.

Summary

  • EventEmitter lets an object announce events; on/once subscribe, off unsubscribes, emit triggers listeners synchronously in registration order.
  • prependListener puts a listener first; emit returns whether any listener ran; listeners run with this set to the emitter (not for arrow functions).
  • Emitting 'error' with no listener throws; always attach an 'error' listener and emit real Error objects.
  • events.once returns a promise for one emission; events.on returns an async iterator; both work with AbortSignal and reject on 'error'.
  • Async listeners lose their rejections unless the emitter is created with captureRejections: true.
  • More than 10 listeners per event triggers a leak warning; remove listeners you add dynamically.
  • EventTarget/Event/CustomEvent are the standard browser equivalents and are available in Node.

Next: Errors and Error Handling