EventEmitter
Node.js uses events extensively. The EventEmitter class allows objects to emit named events and allows listeners to subscribe to them.
Event-driven design can decouple producers from consumers, but excessive event usage can make application flow difficult to understand. Use events when they represent meaningful domain or infrastructure events.
Custom EventEmitter
import { EventEmitter } from 'node:events';
const emitter = new EventEmitter();
emitter.on('user.created', (user) => {
console.log('Created:', user.name);
});
emitter.emit('user.created', { name: 'Suriya' });💡 A listener subscribes to a custom event, and the application emits that event with a user object.
Key Takeaways
- EventEmitter provides publish-subscribe behavior inside a process.
- Listeners should be removed when their lifecycle requires it.
- Use events carefully to avoid hidden control flow.
Knowledge Check
Which method emits an EventEmitter event?