Understanding Event Emitters in Node.js: How and When to Use Them
Source: Dev.to
What Are Event Emitters in Node.js?
Event Emitters in Node.js are a core part of its asynchronous, event‑driven architecture. They allow communication between different parts of an application by emitting named events and responding to them with registered callback functions.
How Do Event Emitters Work?
- Node.js provides the
eventsmodule with theEventEmitterclass. - Objects derived from
EventEmittercan register event listeners and emit events asynchronously. - Listener functions execute each time the event is emitted.
Example: Basic Usage
const EventEmitter = require('events');
const emitter = new EventEmitter();
// Registering an event listener
emitter.on('greet', (name) => {
console.log(`Hello, ${name}!`);
});
// Emitting the event
emitter.emit('greet', 'Alice'); // Output: Hello, Alice!
Common Use Case: Custom Logging System
Suppose you need a custom logging solution across different components:
- Create a logger that emits events when something should be logged.
- Attach listeners to process or store those log events.
Example
const EventEmitter = require('events');
class Logger extends EventEmitter {
log(message) {
this.emit('log', message);
}
}
const logger = new Logger();
// Listen for log events
logger.on('log', (msg) => {
console.log(`Log: ${msg}`);
});
logger.log('Server started'); // Output: Log: Server started
Summary
- Use Event Emitters for loosely coupled communication between different parts of a Node.js application.
- Ideal for custom events, streaming APIs, or building modular systems.
You can extend or reuse EventEmitter to create powerful, modular Node.js applications.