javascript / intermediate
Snippet
Decoupling Systems with EventEmitter
The EventEmitter class is central to Node.js's asynchronous architecture. It allows objects to emit named events that cause function objects ('listeners') to be called. This is a powerful pattern for decoupling logic across different modules of an application.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const EventEmitter = require('node:events');class AuditService extends EventEmitter {}const audit = new AuditService();audit.on('access', (user, resource) => {console.log(`Log: ${user} accessed ${resource} at ${new Date()}`);});// In another part of the app:audit.emit('access', 'Admin', 'FinancialReport');
nodejs
Breakdown
1
class AuditService extends EventEmitter {}
Inherits built-in event capabilities using Object-Oriented Programming.
2
audit.emit('access', ...);
Triggers the event and passes data to any registered listeners.