Node.js Masterclass
High-Performance Backends01.Home02.Introduction03.Environment Setup04.Modules & Exports05.File System (fs)06.Path & OS Modules07.Buffer & Streams08.Events & EventEmitter09.HTTP Module10.NPM & Package.json11.Express.js Fundamentals12.Express Routing13.Express Middleware14.RESTful API Development15.Asynchronous Programming16.Error Handling17.Database with Mongoose18.Authentication with JWT19.Environment Variables20.Testing with Jest21.Deployment & PM2
Events & EventEmitter
Node.js is an event-driven environment. Most of its core functionality is built around an idiomatic asynchronous event-driven architecture.
1. The EventEmitter Class
The EventEmitter class is at the heart of this system. It allows objects to "emit" named events that cause "listeners" (functions) to be called.
const EventEmitter = require('events');
// Create an instance of EventEmitter
const myEmitter = new EventEmitter();
// 1. Create an event listener (on)
myEmitter.on('login', (user) => {
console.log(`User ${user} has logged in!`);
});
// 2. Emit the event (emit)
myEmitter.emit('login', 'Pradeep');2. Passing Arguments
You can pass any number of arguments to the listener functions.
myEmitter.on('data_received', (id, status) => {
console.log(`Item ${id} status is ${status}`);
});
myEmitter.emit('data_received', 101, 'Success');3. Practical Example: Custom Logger
You can extend the EventEmitter class to build your own event-driven tools.
class Logger extends EventEmitter {
log(message) {
console.log('Logging:', message);
this.emit('messageLogged', { id: 1, url: 'http://' });
}
}
const logger = new Logger();
logger.on('messageLogged', (arg) => {
console.log('Listener called with:', arg);
});
logger.log('Hello World');Important: Listeners are called synchronously in the order they were registered. However, usually the logic inside them is handled asynchronously.