In Node.js, the EventEmitter
class is a core module that facilitates the implementation of the Observer pattern. It allows objects to emit and listen for events. This mechanism is widely used in Node.js for handling asynchronous operations and building event-driven architectures. Below is an example demonstrating the use of EventEmitter
:
const EventEmitter = require('events');
// Create an instance of EventEmitter
const myEmitter = new EventEmitter();
// Registering an event listener
myEmitter.on('event', (arg1, arg2) => {
console.log('Event occurred with arguments:', arg1, arg2);
});
// Emitting an event
myEmitter.emit('event', 'Argument 1', 'Argument 2');
In this example:
- We create an instance of
EventEmitter
namedmyEmitter
. - We register an event listener for the event named 'event' using the
on
method. The listener takes two arguments,arg1
andarg2
, representing the arguments passed when the event is emitted. - We emit the 'event' with the
emit
method, providing 'Argument 1' and 'Argument 2' as arguments.
When the event is emitted, the associated listener is invoked, and the output will be:
Event occurred with arguments: Argument 1 Argument 2
Handling Events Asynchronouslyโ
EventEmitter
supports asynchronous event handling using async
functions or the setImmediate
function. Here's an example:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('asyncEvent', async (arg) => {
// Simulate an asynchronous operation
await new Promise((resolve) => setTimeout(resolve, 1000));
console.log('Async event completed with argument:', arg);
});
myEmitter.emit('asyncEvent', 'Async Argument');
In this example, the event listener is an asynchronous function that simulates an asynchronous operation using a Promise
. The event emission will not block the execution, and the output will be:
Async event completed with argument: Async Argument
Handling Onceโ
You can use the once
method to register a one-time listener that will be automatically removed after it's invoked once:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.once('onceEvent', () => {
console.log('This listener will be invoked only once.');
});
myEmitter.emit('onceEvent');
myEmitter.emit('onceEvent'); // This will not trigger the listener again
Error Eventsโ
The EventEmitter
emits a special 'error' event if an error occurs and there are no listeners registered for that event. It's a good practice to handle 'error' events to avoid unhandled exceptions:
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('error', (err) => {
console.error('Error occurred:', err.message);
});
myEmitter.emit('error', new Error('Something went wrong'));
By handling 'error' events, you prevent Node.js from terminating your process due to unhandled exceptions.
This is a basic overview of using EventEmitter
in Node.js. It's a versatile tool for building event-driven applications and handling asynchronous workflows.