Event Emitter

In Node.js, the EventEmitter is a core module that allows you to create and handle custom events. It’s a fundamental concept in Node.js and is used extensively throughout the platform, including in many of the built-in modules like HTTP, Streams, and File System modules.

Nodejs follow Event-Driven based architecture so every action is an event in Nodejs like open the file to read is an event.

What is EventEmitter?

EventEmitter is a class that provides a way to emit (or trigger) named events and subscribe to them. This allows different parts of your application to communicate with each other in a decoupled way, making it easier to manage complex systems where multiple components need to interact.

Key Features of EventEmitter

1. Emit Events: The EventEmitter allows an object to emit an event, signaling that something has occurred. Other parts of the program can listen for this event and execute code in response.

2. Add Listeners: You can register listeners (callback functions) for specific events. These listeners will be triggered whenever the corresponding event is emitted.

3. Handle Multiple Events: The EventEmitter can manage multiple events, each with multiple listeners.

4. Asynchronous and Synchronous Events: Events can be handled synchronously (where the event listeners are called immediately) or asynchronously (allowing other code to run before the event listeners are called).

Basic Usage:

1. Importing the events module:


const EventEmitter = require('events');

2. Creating an EventEmitter instance:


const eventEmitter = new EventEmitter();

3. Adding a listener for an event:


var customEventHandler = ()=> { 
console.log('an event occurred!'); 
} 

eventEmitter.on('customEventName', customEventHandler);

4. Emitting an event:


eventEmitter.emit('customEventName');

Example


const EventEmitter = require('events');

// Create an instance of EventEmitter
const myEmitter = new EventEmitter();

// Define a listener for the 'greet' event
myEmitter.on('greet', (name) => {
    console.log(`Hello, ${name}!`);
});

// Emit the 'greet' event with a name as an argument
myEmitter.emit('greet', 'John');

Output:

Hello, John!

Key Methods

Registers a listener for a specific event. This listener will be called every time the event is emitted.

on(eventName, listener):: Emits an event, invoking all the listeners registered for that event, and passing them any provided arguments.

once(eventName, listener): Registers a listener that will be invoked only the first time the event is emitted. After that, it is automatically removed.

removeListener(eventName, listener): Removes a specific listener from an event, so it will no longer be called when the event is emitted.

removeAllListeners([eventName]): Removes all listeners for a given event, or all events if no event name is provided.

Example:

We want to alert everyone when a new user joins the chat room. We’ll need an event listener for a userJoined event. First, we’ll write a function that will act as our event listener, then we can use EventEmitters on the method to set the listener.


const events = require('events');
const chatRoomEvents = new events.EventEmitter;

function userJoined(username){
  // Assuming we already have a function to alert all users.
  alertAllUsers('User ' + username + ' has joined the chat.');
}

// Run the userJoined function when a 'userJoined' event is triggered.
chatRoomEvents.on('userJoined', userJoined);

The next step would be to make sure that our chat room triggers a userJoined event whenever someone logs in so that our event handler is called. EventEmitter has an emit method that we use to trigger the event. We would want to trigger this event from within a login function inside of our chatroom module.


function login(username){
  chatRoomEvents.emit('userJoined', username);
}

there are lots of default events in Nodejs but I am showing some events.


newListener('eventName',listener)

It is called when we want to add listner in the event.


removeListener('eventName',listener);

It is called when we want to remove listner from the event.


once('eventName', listener)

Adds a one-time listener function for the event named eventName