Real life examples of EventEmitter in nodejs
The EventEmitter
in Node.js is a powerful mechanism that allows objects to emit named events that cause registered listeners to be called. It's widely used for building event-driven architectures, where components communicate asynchronously. Here are three real-life examples where EventEmitter
can be applied, along with code examples for each scenario:
1. Notification System
Scenario: Building a notification system where different parts of an application need to react to events such as new messages, user actions, or system alerts.
Example Code:
const EventEmitter = require('events');
// NotificationService emits events for notifications
class NotificationService extends EventEmitter {
sendNotification(message) {
console.log('Sending notification:', message);
this.emit('notification', message);
}
}
// Usage example
const notificationService = new NotificationService();
// Subscriber 1: Email notification listener
notificationService.on('notification', (message) => {
console.log('Email notification sent:', message);
});
// Subscriber 2: SMS notification listener
notificationService.on('notification', (message) => {
console.log('SMS notification sent:', message);
});
// Send notifications
notificationService.sendNotification('New message received');
notificationService.sendNotification('Server down alert');
Explanation:
NotificationService
extendsEventEmitter
, allowing it to emit'notification'
events.- Subscribers (listeners) register with
.on('notification', callback)
to receive notifications. sendNotification(message)
method emits'notification'
events with the provided message, triggering all registered listeners.
2. Logging System
Scenario: Implementing a logging system where various parts of an application log events, errors, and information to different outputs (e.g., console, files).
Example Code:
const EventEmitter = require('events');
const fs = require('fs');
class Logger extends EventEmitter {
log(message) {
console.log('Logging message:', message);
this.emit('log', message);
}
}
const logger = new Logger();
// Subscriber 1: Console logging
logger.on('log', (message) => {
console.log('Console log:', message);
});
// Subscriber 2: File logging
logger.on('log', (message) => {
fs.appendFile('app.log', `${message}\n`, (err) => {
if (err) throw err;
console.log('File log saved');
});
});
// Log messages
logger.log('User login successful');
logger.log('Database connection failed');
Explanation:
Logger
extendsEventEmitter
to emit'log'
events with messages.- Multiple listeners subscribe to
'log'
events to perform actions (console logging, file writing). log(message)
method emits'log'
events, triggering all registered listeners to log messages accordingly.
3. User Authentication and Authorization
Scenario: Implementing a user authentication system where components need to react to events like user login, logout, or access permission changes.
Example Code:
const EventEmitter = require('events');
class AuthSystem extends EventEmitter {
login(username) {
console.log('User logged in:', username);
this.emit('login', username);
}
logout(username) {
console.log('User logged out:', username);
this.emit('logout', username);
}
}
const authSystem = new AuthSystem();
// Subscriber 1: Audit log listener
authSystem.on('login', (username) => {
console.log('Audit log: User logged in -', username);
});
// Subscriber 2: Access control listener
authSystem.on('login', (username) => {
console.log('Access control: Granting permissions for user -', username);
});
// Usage example
authSystem.login('alice');
authSystem.logout('alice');
Explanation:
AuthSystem
extendsEventEmitter
to emit'login'
and'logout'
events with usernames.- Listeners (
'login'
and'logout'
) react to events, performing actions such as audit logging and access control updates. - Methods like
login(username)
andlogout(username)
emit corresponding events, notifying all subscribers.