Loading...
Loading...

Node.js Event Emitter

Node.js Event Emitter is a fundamental part of the Node.js core API that allows developers to create custom events and listeners for handling events in an application.

1. What is Event Emitter?

In Node.js, the EventEmitter class allows objects to emit named events and register listener functions that respond to those events. It is used heavily in the core of Node.js.

2. Using the EventEmitter Class

To use EventEmitter, you must import the `events` module:

const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

eventEmitter.on('greet', () => {
    console.log('Hello, World!');
});

eventEmitter.emit('greet');  // Output: Hello, World!

This example creates an instance of EventEmitter, adds a listener for the 'greet' event, and emits it, logging "Hello, World!" to the console.

3. Passing Arguments to Event Handlers

Event listeners can accept arguments, and these arguments will be passed when the event is emitted:

eventEmitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});

eventEmitter.emit('greet', 'Alice');  // Output: Hello, Alice!

Here, we pass an argument (`'Alice'`) to the event handler, which is logged in the output.

4. Removing Event Listeners

To stop listening to an event, you can remove the event handler using the `removeListener` or `off` method:

const greetHandler = (name) => {
    console.log(`Hello, ${name}!`);
};

eventEmitter.on('greet', greetHandler);
eventEmitter.removeListener('greet', greetHandler);

eventEmitter.emit('greet', 'Bob');  // No output

In this example, we remove the `greetHandler` listener and the event is no longer triggered when emitted.

5. Handling Multiple Event Listeners

Multiple listeners can be attached to the same event. Each listener will be called when the event is emitted:

eventEmitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});

eventEmitter.on('greet', (name) => {
    console.log(`Welcome, ${name}!`);
});

eventEmitter.emit('greet', 'Charlie');  
// Output: 
// Hello, Charlie!
// Welcome, Charlie!

This example demonstrates that multiple listeners can handle the same event.

6. Conclusion

Node.js Event Emitter is a powerful tool for handling custom events in an application. By using the `EventEmitter` class, you can manage event-driven programming, making your code more flexible and modular.

0 Interaction
1.5K Views
Views
49 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home