EventEmitter In Depth
once runs a listener a single time, off removes one, and the special error event throws if nobody listens. Always attach an error listener to emitters that can fail.
Example
const EventEmitter = require('node:events');
const e = new EventEmitter();
e.once('hi', () => console.log('first only'));
e.on('hi', () => console.log('every time'));
e.emit('hi'); e.emit('hi');
console.log(e.listenerCount('hi'));
e.on('error', (err) => console.log('caught', err.message));
e.emit('error', new Error('boom'));Result
first only every time every time 1 caught boom
Exercise
Listen one time.
e.("x", fn)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.