Event errors and listener lifetime
Local practice: Node.js 22.16.0 on Linux x64; proposed teaching baseline 26.13.1 remains untested. Copy only the listed files into a fresh disposable directory. No dependency installation or external services required. These are static Node.js examples, not verified ByteMind runner tasks.
Handle a synthetic error and unsubscribe
import { EventEmitter } from 'node:events';const job = new EventEmitter();const report = err => console.log('failed:', err.message);job.on('error', report);job.emit('error', new Error('inventory unavailable'));job.off('error', report);console.log(job.listenerCount('error'));Run:
node main.mjsExpected stdout:
failed: inventory unavailable0Exit status: 0. Expected stderr: empty.
How it works
Attach an error listener before the emitter can fail; decide whether the application can recover. A synchronous exception thrown by an ordinary listener propagates out of emit, and a rejected promise returned by an async listener is not automatically awaited. The events.once(emitter, name, { signal }) helper returns a promise of event arguments, with rejection on error (unless waiting for error itself) or cancellation. Register all waits before emitting; serial awaits can miss synchronous events. events.on offers async iteration for repeated events; consumers need termination and capacity planning.
Wait for a one-time event
import { EventEmitter, once } from 'node:events';const bus = new EventEmitter();const completion = once(bus, 'ready');bus.emit('ready', 'catalog', 3);const [name, count] = await completion;console.log(name, count, bus.listenerCount('ready'));Run:
node main.mjsExpected stdout:
catalog 3 0Exit status: 0. Expected stderr: empty.
Common mistake
Increasing a max-listener warning threshold does not fix a leak. Remove subscriptions when their owner stops; a listener count is a diagnostic hint, not proof of a leak.
Practice
Add a second subscription with a separate owner and remove only the first. In the once example, abort the wait instead of emitting a result and handle the rejection.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Event errors and listener lifetime — knowledge check
Apply the concepts and predict the behavior taught in this lesson.
What happens if error is emitted without an error listener?
When should a one-shot event wait be registered?
What is a suitable first response to an unexpected growing listener count?