BeginnerLesson 5 of 126 min read

Events and the EventEmitter: Programs That React

Build programs from events with the EventEmitter class: register listeners, emit events with data, use once, remove listeners, understand synchronous delivery and the special error event, and verify the behaviour against an independent implementation.

In this lesson you will

  • Use on, emit, once and off
  • Know the order and timing of listeners
  • Handle the special error event
  • Design a small event-driven component

About 28 minutes

When an order arrives, many things should happen

When a new order comes in at Mara’s shop, several things should happen: it is logged, the job sheet is updated, the customer gets a message, and a stock counter goes down. If the code that receives the order calls all four functions directly, it must know about every one of them, and adding a fifth means editing it. Node’s EventEmitter inverts this. The component that receives orders only announces what happened, with emitter.emit(“order”, data), and anything that cares registers a listener with emitter.on(“order”, handler). The announcer does not know who listens, and listeners can be added or removed without touching it. Much of Node is built this way: servers, streams and processes are all event emitters.

A few rules make emitters predictable. Listeners are called synchronously, in the order they were registered, before emit returns, and emit returns true if there was at least one listener. once registers a listener that removes itself after the first call, off removes one, and prependListener puts a listener at the front. The event named error is special: if a listener is missing when it is emitted, Node throws the error, which usually crashes the program, so every emitter that can fail needs an error listener. Because delivery is synchronous, a slow listener delays all the following ones and the code that called emit, and an exception in a listener travels up to the emitter’s caller.

Method Effect
on(name, f) Call f every time
once(name, f) Call f once, then remove it
off(name, f) Remove f
emit(name, …args) Call all listeners now, return true if any
prependListener(name, f) Put f first
listenerCount(name) How many listeners
const EventEmitter = require('events');
const log = [];
class Shop extends EventEmitter {
  receive(order) { log.push('receive ' + order.id); const heard = this.emit('order', order); log.push('emit returned ' + heard + ' for order ' + order.id); }
}
const shop = new Shop();
const stock = { poster: 10 };
const first = o => log.push('log: order ' + o.id + ' (' + o.qty + ' x ' + o.item + ')');
shop.on('order', first);
shop.on('order', o => { stock[o.item] -= o.qty; log.push('stock of ' + o.item + ' is now ' + stock[o.item]); });
shop.once('order', o => log.push('welcome message for order ' + o.id));
shop.prependListener('order', o => log.push('audit: order ' + o.id));
log.push('listeners: ' + shop.listenerCount('order'));
shop.receive({ id: 1, item: 'poster', qty: 3 });
shop.off('order', first);
shop.receive({ id: 2, item: 'poster', qty: 2 });
log.push('listeners now: ' + shop.listenerCount('order'));
log.push('emit with nobody listening returns ' + shop.emit('nothing'));
let caught = null;
try { shop.emit('error', new Error('printer jammed')); } catch (e) { caught = e.message; }
log.push('error event without a listener threw: ' + caught);
shop.on('error', e => log.push('error handled: ' + e.message));
shop.emit('error', new Error('printer jammed'));
log.forEach(l => console.log(l));
const { spawnSync } = require('child_process');
const un = spawnSync(process.execPath, ['-e', "new (require('events'))().emit('error', new Error('x'))"], { encoding: 'utf8' });
console.log('unhandled error event in a child: exit status', un.status);
console.log('DATA ' + JSON.stringify({ log, un: un.status }));
listeners: 4
receive 1
audit: order 1
log: order 1 (3 x poster)
stock of poster is now 7
welcome message for order 1
emit returned true for order 1
receive 2
audit: order 2
stock of poster is now 5
emit returned true for order 2
listeners now: 2
emit with nobody listening returns false
error event without a listener threw: printer jammed
error handled: printer jammed
unhandled error event in a child: exit status 1

The log shows the story of two orders, in the exact order of events. Before any order, there are 4 listeners. For order 1, the announcer logs “receive 1”, then the listeners run in their order: the audit listener, added last with prependListener but placed first, then the log line, then the stock update, then the one-time welcome message, and then emit returns true, because somebody listened. After the first order, the once listener removed itself, and the log listener was removed with off, so order 2 shows only the audit and the stock update: the stock of posters went from 10 to 7 and then to 5.

The last lines show the error rules. Emitting “nothing” with no listeners returns false and does nothing. Emitting an “error” event with no listener throws the error, so the first attempt was caught as “printer jammed”, and a child process that did the same without catching exited with status 1. After an error listener was added, the same emit was handled quietly and logged. In real programs, every emitter that can fail, such as a stream or a connection, must have an error listener, or a single failure ends the process.

Independent check: the same sequence of operations was run on a second implementation, a small emitter written in Python from the rules in the documentation: lists of listeners, once flags that remove an entry, prepend, off and the special treatment of the error event. Its log is identical to Node’s line by line, which shows that the rules in the text, and not only the output, describe the real behaviour, including the ordering of the prepended listener.

Check by hand: ten posters minus 3 is 7, and minus 2 is 5. Four listeners are registered at the start, audit, log, stock and welcome. After the first order the welcome one is gone and after off the log one is gone, so two remain, as the output states.

Always handle the error event

A missing error listener turns a recoverable problem into a crash. Add one to every emitter that can fail, even if it only logs.

Remove listeners you no longer need

A listener that is never removed keeps its objects alive, and adding listeners in a loop makes memory grow. Node warns after more than ten listeners for one event, which is usually a sign of this mistake.

About this course

Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation.

Practice

Add a “refund” event and a listener that increases the stock. Use once to run a start-up message. Write a class that extends EventEmitter and emits “progress” events while it processes a list.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

When are listeners called?

  1. Later, in random order
  2. Synchronously, in registration order, during emit
  3. On the next tick
  4. After a timer

Before emit returns.

What does once do?

  1. Calls the listener one time, then removes it
  2. Calls it once per second
  3. Stops the emitter
  4. Emits an event once

Good for start-up events.

What happens when “error” is emitted with no listener?

  1. The error is thrown
  2. Nothing
  3. A warning is printed
  4. It is retried

Usually crashing the program.

What does prependListener do?

  1. Removes a listener
  2. Emits an event
  3. Sorts listeners
  4. Puts the listener first

The default adds at the end.

What does emit return?

  1. The listeners
  2. The data
  3. Nothing
  4. true if there was at least one listener

false if none.

Summary

  • Emitters announce events and listeners react.
  • Listeners run synchronously in registration order.
  • once, off and prependListener control the list.
  • An unhandled error event throws: always add a listener.

Next lesson

Lesson 6 covers streams.

Questions

Is EventEmitter asynchronous?

No, listeners run synchronously. Combine it with promises or setImmediate when you want to defer work.

What is the difference between on and once?

on keeps the listener for every event, and once removes it after the first.

Why extend EventEmitter?

So that your own class can announce events. Streams, servers and many libraries do this.

Progress is saved in this browser.