Event Modules in Node js
In Node.js, the Event module provides a way to handle and work with events. It is a core module that enables event-driven programming, which is central to Node.js's architecture.
Key Concepts of the Event Module
EventEmitter:
The EventEmitter
class is the core of the event module. It allows you to create, listen to, and emit events.
Event Listeners:
You can register functions (listeners) to handle specific events when they are emitted.
Basic Usage
Here’s an example to illustrate how the Event module works:
Import the Event Module
const EventEmitter = require('events');
Create an EventEmitter Instance
const eventEmitter = new EventEmitter();
Add Event Listeners
// Adding a listener for the 'greet' eventeventEmitter.on('greet', (name) => { console.log(`Hello, ${name}!`);});
Emit Events
// Emitting the 'greet' eventeventEmitter.emit('greet', 'Alice');
Common Methods
Adding Listeners
on(eventName, listener)
: Attaches a listener to the event.once(eventName, listener)
: Attaches a one-time listener.
on(eventName, listener)
: Attaches a listener to the event.once(eventName, listener)
: Attaches a one-time listener.
Removing Listeners
removeListener(eventName, listener)
: Removes a specific listener.removeAllListeners([eventName])
: Removes all listeners for the specified event.
removeListener(eventName, listener)
: Removes a specific listener.removeAllListeners([eventName])
: Removes all listeners for the specified event.
Emitting Events
emit(eventName, [...args])
: Triggers the event and passes arguments
to the listeners.
emit(eventName, [...args])
: Triggers the event and passes arguments to the listeners.
Other Utility Methods
listenerCount(eventName)
: Returns the number of listeners for an event.eventNames()
: Returns an array of event names.
listenerCount(eventName)
: Returns the number of listeners for an event.eventNames()
: Returns an array of event names.