Ticker

6/recent/ticker-posts

Node.js EventEmitter

Node.js EventEmitter

Introduction
The Node.js EventEmitter is a class within the Node.js core modules that enables communication between objects in a publish-subscribe pattern. It allows certain objects, called "emitters," to emit named events and other objects, known as "listeners," to subscribe and respond to those events.

Basic Usage
To use EventEmitter, you need to import it first:

javascript
const EventEmitter = require('events');

Creating an EventEmitter Instance
You can create an EventEmitter instance by extending the EventEmitter class:

javascript
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();

Subscribing to an Event
You can listen for an event using the on method:

javascript
myEmitter.on('eventName', (arg1, arg2) => {
console.log('Event triggered with arguments:', arg1, arg2);
});

Emitting an Event
To emit an event and trigger all subscribed listeners, use the emit method:

javascript
myEmitter.emit('eventName', 'arg1Value', 'arg2Value');

Removing Event Listeners
You can remove a specific event listener using the off or removeListener method:

javascript
function eventHandler() {
console.log('Event handled!');
}

myEmitter.on('eventName', eventHandler);

// Remove the event listener
myEmitter.off('eventName', eventHandler);

Once Method
If you want an event listener to be executed only once, use the once method:

javascript
myEmitter.once('eventName', () => {
console.log('This listener will be executed only once.');
});

Error Events
Node.js has a special event named 'error' that handles uncaught errors. It should be handled to prevent crashes:

javascript
myEmitter.on('error', (err) => {
console.error('Error occurred:', err.message);
});

Conclusion
Node.js EventEmitter is a powerful tool for handling events and enabling communication between different parts of your Node.js application in an efficient and organized manner. By using the EventEmitter class, you can build scalable and event-driven applications.

Remember to handle errors properly using the 'error' event to prevent unexpected crashes and improve the robustness of your code.

Post a Comment

0 Comments