Event emitters: on, once and emit
A promise is one result for one caller, and an event is one message for however many listeners are interested. EventEmitter from node:events is the object behind that idea: a listener is registered with a name, a call runs every listener of that name, and a listener can remove itself afterwards. The class ships with the runtime, so it is one import and no package from npm.
The lesson takes the two methods that carry the pattern, on and emit, the once that removes itself, the two ways to remove a listener, and the event named error, which is the one the runtime refuses to drop. It closes the part of the course about asynchronous code.
on and emit
on(name, listener) adds a listener and emit(name, ...args) calls every listener of that name synchronously, in the order they were added, with the arguments that followed the name. The return value of emit says whether anyone was listening.
The file emit.mjs:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on('save', (name) => {
console.log('a listener heard the save of', name);
});
emitter.on('save', (name) => {
console.log('a second listener heard it too:', name);
});
console.log('the listener count:', emitter.listenerCount('save'));
emitter.emit('save', 'notes.txt');
console.log('an event nobody listens to returns:', emitter.emit('nothing'));
node emit.mjs
the listener count: 2
a listener heard the save of notes.txt
a second listener heard it too: notes.txt
an event nobody listens to returns: false
Both listeners ran inside the call to emit, in the order they were registered, and the count was taken before the event. The false at the end is the difference between on and a callback stored in a variable: an event with no listener is not an error, it is simply not heard.
once
once registers a listener that removes itself after its first call. It is the method for the event that happens one time, such as a connection that is ready or a file that is loaded, because the listener has no reason to run again and a program that keeps it would run it twice.
The file once.mjs:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.once('ready', () => {
console.log('the once listener ran');
});
emitter.on('ready', () => {
console.log('the on listener ran');
});
emitter.emit('ready');
emitter.emit('ready');
console.log('the count after two emits:', emitter.listenerCount('ready'));
node once.mjs
the once listener ran
the on listener ran
the on listener ran
the count after two emits: 1
The first emit reached both listeners, and the second reached only the one from on, which is why the count is one. A listener that forgets to remove itself is the usual cause of a handler that runs twice and of the warning that Node.js prints when an emitter has more than ten listeners.
off and removeAllListeners
A listener is removed by the same function that was registered: off(name, listener) compares the function itself, so an anonymous arrow cannot be removed later. removeAllListeners(name) clears the whole event, which is what a cleanup path does when it owns the emitter.
The file remove.mjs:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
const onData = (value) => {
console.log('the listener got', value);
};
emitter.on('data', onData);
emitter.emit('data', 1);
emitter.off('data', onData);
emitter.emit('data', 2);
console.log('the count after off:', emitter.listenerCount('data'));
emitter.on('data', () => {
console.log('one');
});
emitter.on('data', () => {
console.log('two');
});
emitter.removeAllListeners('data');
console.log('the count after removeAllListeners:', emitter.listenerCount('data'));
node remove.mjs
the listener got 1
the count after off: 0
the count after removeAllListeners: 0
The second event was not heard, and the two anonymous listeners went at once with removeAllListeners. Keeping the function in a binding is the habit that makes the first form possible, and it is also what a test uses to check that a cleanup really removed what it added.
The error event
The event named error is special: with a listener it behaves like any other event, and without one the emitter throws the value and the process ends with one. That is a deliberate design, so a failure of a stream or a socket cannot pass unnoticed because nobody subscribed.
The file error.mjs:
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on('error', (error) => {
console.log('a listener handled it:', error.message);
});
emitter.emit('error', new Error('something broke'));
console.log('now the same event without a listener');
const bare = new EventEmitter();
bare.emit('error', new Error('nothing handles this'));
node error.mjs
echo "exit code: $?"
a listener handled it: something broke
now the same event without a listener
exit code: 1
The first emitter had a listener and the message was handled; the second had none, so the throw left the program and it ended with one. The stack on standard error is the error itself with the frame of the emit call, which is why the block above keeps to standard output and the code. An emitter that a program creates itself should always be given an error listener, whatever else it does.
Exercises
- Add a third listener to the first program and print the count again. How many lines does one emit produce?
- Emit an event with two arguments and print both in the listener.
- Register the same function twice with on and emit once. How many times does it run?
- Remove a listener from inside itself with off and emit twice. Which call prints?
- Add a second error listener and check which of the two runs first. Does the first one stop the second?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does emit return?
Answer
true when at least one listener ran
The boolean says whether the event was heard, which is how a caller can tell.
-
Where does EventEmitter come from?
Answer
The node:events module
The class ships with Node.js, and the import is the only setup a program needs.
-
What does once do?
Answer
It removes the listener after its first call
A once listener runs for the first event and is gone for the second.
-
What happens when an error event has no listener?
Answer
The emitter throws and the process exits with 1
The error event is special precisely so that a failure cannot be dropped silently.
-
What does this program print?
import { EventEmitter } from "node:events"; const emitter = new EventEmitter(); emitter.on("hi", (name) => console.log("hi", name)); emitter.emit("hi", "Ada");Answer
hi Ada
The arguments after the event name are passed to the listener in order.
-
What does this program print?
import { EventEmitter } from "node:events"; const emitter = new EventEmitter(); emitter.once("ping", () => console.log("pong")); emitter.emit("ping"); emitter.emit("ping");Answer
pong
The listener removed itself after the first emit, so the second one found nobody.
-
What does this program print?
import { EventEmitter } from "node:events"; const emitter = new EventEmitter(); console.log(emitter.listenerCount("x"));Answer
0
An event with no listeners has a count of zero, and asking does not create it.
-
What is a listener called with?
Answer
The arguments that followed the event name in emit
The rest of the arguments of emit arrive in the listener in the same order.
-
Which listener can be removed later with off?
Answer
One kept in a binding, because off compares the function
The removal looks for the same function, and an arrow that is not stored cannot be passed again.
-
What does this program print?
import { EventEmitter } from "node:events"; const emitter = new EventEmitter(); const listener = () => console.log("called"); emitter.on("x", listener); emitter.off("x", listener); console.log(emitter.listenerCount("x"));Answer
0
The same function was removed before any emit, so the event has no listeners.
The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev