Full answer
Many core classes (streams, servers, sockets, processes) extend EventEmitter. It is Node's version of the observer pattern.
Main methods:
- emitter.on(name, listener) or addListener: add a listener.
- emitter.once(name, listener): the listener runs at most once.
- emitter.off(name, listener) or removeListener: remove it.
- emitter.emit(name, ...args): call every listener with the arguments. Returns true if there was at least one listener.
- emitter.listenerCount(name) and eventNames().
Key behaviours:
- emit is synchronous. All listeners finish before emit returns, in the order of registration. A slow listener blocks the emitter, and a listener that throws stops the remaining listeners and the exception goes to the caller of emit.
- Listeners are called with this set to the emitter (not for arrow functions).
- The event name 'error' is special. If emit('error', err) is called and no 'error' listener exists, the error is thrown. Always add an error listener to emitters that can fail, such as streams and sockets.
- Emitting before anyone listens means the event is lost. Add listeners first.
To build your own, extend the class: class Order extends EventEmitter. Remember to call super() in the constructor.
const { EventEmitter } = require('node:events');
class Attendance extends EventEmitter {
mark(student, present) {
this.emit('marked', student, present);
if (!present) this.emit('absent', student);
}
}
const register = new Attendance();
register.on('marked', (student, present) => console.log('1. marked', student, present));
register.on('marked', (student) => console.log('2. second listener for', student));
register.once('absent', (student) => console.log('3. absence alert (once) for', student));
register.mark('Asha', true);
register.mark('Ravi', false);
register.mark('Meera', false); // the once listener is gone, no alert
console.log('absent listeners left:', register.listenerCount('absent'));
// emit is synchronous
register.on('ping', () => console.log('listener ran'));
register.emit('ping');
console.log('emit returned after the listener finished');
// 'error' without a listener throws
try {
register.emit('error', new Error('database offline'));
} catch (err) {
console.log('thrown because nobody listened:', err.message);
}The alert for Meera does not print, because the once listener removed itself after the first absence. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): 1. marked Asha true 2. second listener for Asha 1. marked Ravi false 2. second listener for Ravi 3. absence alert (once) for Ravi 1. marked Meera false 2. second listener for Meera absent listeners left: 0 listener ran emit returned after the listener finished thrown because nobody listened: database offline
Key points
- on, once, off and emit are the core API.
- emit calls listeners synchronously in registration order.
- An 'error' event without a listener throws.
- Events emitted before listeners are attached are lost.
Common mistakes
- Assuming emit is asynchronous.
- Forgetting an 'error' listener and crashing the process.
- Adding a listener after the event was already emitted.
- Using an arrow function and expecting this to be the emitter.
Follow-ups
- How would you make listeners run asynchronously?
- What does emitter.prependListener do?
- How does EventEmitter relate to streams?
Tips
- Say 'synchronous' and 'error is special' without being asked.
- Give a realistic example such as an order or attendance system.
- Mention that streams, HTTP servers and sockets are emitters.