In Node.js, you can create custom events using the ‘EventEmitter‘ class which is a part of the ‘events‘ module. The ‘EventEmitter‘ class provides a way for you to create named events and associate event handlers with them. Here’s a step-by-step guide on how to create custom events using the ‘EventEmitter‘ class:
1. Import the ‘events‘ module:
const events = require('events');
2. Create a new instance of the ‘EventEmitter‘ class:
const eventEmitter = new events.EventEmitter();
3. Define custom event(s) using the ‘on()‘ method or the ‘addListener()‘ method:
eventEmitter.on('myEvent', (message) => {
console.log(`Received: ${message}`);
});
4. Emit the custom event(s) using the ‘emit()‘ method:
eventEmitter.emit('myEvent', 'Hello, EventEmitter!');
Here’s a complete example:
// Import the 'events' module
const events = require('events');
// Create a new instance of the 'EventEmitter' class
const eventEmitter = new events.EventEmitter();
// Define a custom event called 'myEvent' and its associated event handler
eventEmitter.on('myEvent', (message) => {
console.log(`Received: ${message}`);
});
// Trigger the custom event 'myEvent' with a custom message
eventEmitter.emit('myEvent', 'Hello, EventEmitter!');
When you run this code, you’ll see the following output:
Received: Hello, EventEmitter!
You can also define multiple event handlers for the same event by using the ‘on()‘ method multiple times:
eventEmitter.on('myEvent', (message) => {
console.log(`Handler 1: ${message}`);
});
eventEmitter.on('myEvent', (message) => {
console.log(`Handler 2: ${message}`);
});
Now, when you emit the ‘myEvent‘, both handlers will be executed:
Handler 1: Hello, EventEmitter!
Handler 2: Hello, EventEmitter!
Feel free to ask if you need more clarification or additional examples!