Nodejs Event Emitter

FREE Online Courses: Your Passport to Excellence - Start Now

Events is a built-in module in node.js. In order to include it you have to use the “require” function. To use the functionalities of events like create, emit or listen we have to instantiate the eventemitter class. Let us learn about event emitter in nodejs.

Event-Driven programming:

When nodejs starts a server it initializes all its variables, declares functions, and keeps waiting for an event to happen. That is why node js applications are known as event-driven applications.

Event:

Event module in nodejs is a built-in module, this module contains the event emitter class which is used to implement event driven programming. To use this module in our file we use the require() function.

Event emitter class generates the events in nodejs. The event emitter class and the javascript callbacks handles the event.

Event and its working:

Whenever any event occurs first the corresponding event handler is triggered. The call back function then executes, and the main loop keeps on listening for any new event triggers and calls the corresponding event handler.

Event Emitter and its working

Event Emitter is a class that is capable of emitting an event, attaching an event and also detaching it.

Https and other node js core modules use the event emitter class.

The event emitter class calls all the events in the same order in which they were registered.

The on() method is used to attach the event handler, this method takes a callback function that gets attached to the event. More than one function can also be attached to a single event.

Technology is evolving rapidly!
Stay updated with DataFlair on WhatsApp!!

The emit() method is used to emit the attached event, basically, it invokes the attached function.

Code for event emitter:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1() {
    console.log('First event occurred!')
}
 
function event2() {
    console.log('First event occurred!')
}
 
emitter.on('someevent', event1)
emitter.on('someevent', event2)
emitter.emit('someevent')

Output:

node.js emit method

In the above image, you can see that the function event1 and event 2 has been registered by the name “someevent” using the on() method.

Next, we used the emit method to fire the event and we can see the output of both the functions which means that both the functions were invoked as soon as the “someevent” event was fired.

Emitting event with parameter.

We can also pass data to the call-back function. In order to do so, we have to pass the data in the second argument of emit() method.

Code for event emitter with parameter:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.on('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })

Output:

node.js addlistener

You can see that we have passed a name with value “DataFlair” in our second argument. This value is then used by the event1 function.

Event Emitter Methods:

Below are the methods present in the event emitter with explanation and code.

Detach Event;

We can detach the previously attached event by using the off() method.

Code for detaching event:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.on('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
emitter.off('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })

Output

node.js detach method

You can see that we have used emit method twice to emit the same event but the output came only for that emit which was called before detaching the event using the off() method.

So once you detach an event then the emit method does not have any effect for that event.

Count Listener:

listenerCount() method returns the number of listeners for that event.

You can see in the below image that listenerCount() return 1 at first than as we called the off() method the listener for the event is detached and hence the count of listener is now zero

Code for count listener:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.on('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
console.log(emitter.listenerCount('someevent'))
emitter.off('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
console.log(emitter.listenerCount('someevent'))

Output:

node.js listener count

Raw Listener:

It returns an array of listeners for that particular event.

Code for raw listener:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.on('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
console.log(emitter.rawListeners('someevent'))
emitter.off('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
console.log(emitter.rawListeners('someevent'))

Output:

node.js raw listener

Before calling the off() method there was one listener so it returned its type and name. After the off() method was called nothing was attached to the event so it returned an empty array.

Add Listener:

This is similar to the on method. It takes the event name and a callback function and then attaches the event. It checks the event array to see if the event has already been attached or not. If the event is attached it returns the array, else return empty array.

Code for adding listener:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.addListener('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })

Output:

node.js addlistener

You can see that the result is same as the on() method

Remove Listener:

It is similar to the off() method. It checks in the event array for the event and it removes it from the event array.

Code for removing listener:

const EventEmitter = require('events');
const emitter = new EventEmitter();
 
function event1(arg) {
    console.log('Welcome to', arg.name);
}
 
emitter.addListener('someevent', event1)
emitter.emit('someevent', { name: "DataFlair" })
emitter.removeListener('someevent', event1);
emitter.emit('someevent', { name: "DataFlair" })

Output:

node.js removelistener

The answer is the same as that for the off() method.

Once:

If we want an event to be used only one time then we can use the once() method. It takes eventname and a callback function.

When the event is first emitted it invokes the callback function and after that it detaches the event automatically, after that It will not respond to any more emitted calls.

Code for once:

const EventEmitter = require('events');
const emitter = new EventEmitter();
function event1() {
    console.log('Welcome to DataFlair');
}
emitter.once('someevent', event1)
emitter.emit('someevent')
emitter.emit('someevent')

Output:

node.js once emitter

You can see that the once method invoked the callback function only when the first emit() method executed, the next emit method did not invoke the callback function as the event already got detached.

Summary

In this article, we have seen the builtin event module of node js and its methods. We hope you enjoyed the article.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *