EventEmitter
The core class for emitting named events and registering listeners.
Syntax
class extends EventEmitter {} / new EventEmitter() Returns
EventEmitter — An emitter instance with on, once, emit, and off.
Examples
import { EventEmitter } from 'node:events';
class Job extends EventEmitter {}
const job = new Job();
job.on('done', (id) => console.log('finished', id));
job.emit('done', 7);
Output
finished 7
import { EventEmitter, once } from 'node:events';
const ee = new EventEmitter();
setTimeout(() => ee.emit('ready', 'go'), 10);
const [msg] = await once(ee, 'ready');
console.log(msg);
Output
go
Notes
Many Node objects (streams, servers, process) are EventEmitters. An
`'error'` event with no listener throws and can crash the process,
so always attach an error handler. Adding more than 10 listeners for
one event logs a leak warning.