What is EventEmitter in Nodejs?

Konfinity
March 5,2021 - 9 min read
What is EventEmitter in Nodejs?

Nodejs is a powerful Javascript framework used to develop server-side, networking applications. It is also used to make applications interacting with hardware and other common purpose software applications. These applications built with the help of Nodejs are fast along with being very scalable. Nodejs has the ability to create dynamic content on webpages. It collects data produced through forms and modify the particular database you are using in your project. Nodejs is an open-source project which provides a runtime environment for Javascript. Nodejs and other related frameworks have popularized and increased the demand for Javascript amongst the developer community.

Nodejs has a large set of modules that aid the development process of any application. There are a lot of features like advanced and customised request handling, efficient package managers like NPM and YARN in Nodejs. However, in this blog, we are going to talk about the asynchronous and event-based nature of Nodejs that allows developers to create fully advanced applications beginning right from scratch. Let’s get started with the basic concepts and important terms involved with event driven programming.

Event Driven Programming

Event-driven programming is the core concept of Nodejs. This style of programming in NodeJS is achieved with the help of event-emitter class. This blog is dedicated to a discussion on event-emitter class where we will talk about the core concept, the technique, algorithm and process of creating an event emitter class along with attaching event listeners and publishing events to an event emitter. We would look at the basics of maintaining a single event-emitter instance in the entire application, the sequence of execution of event emitters and look at questions like whether the event emitter class is synchronous or not. This blog will help you understand event emitters and their use in Nodejs along with useful member functions of this class. Let’s get started

EventEmitter in Nodejs

In this segment, we are going to talk about the class in Nodejs that creates a publisher-subscriber pattern in NodeJS. This class is the EventEmitter class in Nodejs. This class helps developers raise a new event from various parts of an application. A listener is used to listen and perform some action for the event. In the next segment, we are going to discuss how an Event Emitter is created in Nodejs.

Creating an Event Emitter

We will create an even emitter with the help of the Typescript language. When creating an even emitter, it is essential to create an instance of the event emitter from the events module in NodeJS. The code for making an instance of EvenEmitter will look like this -

  • import { EventEmitter } from 'events';
  • const eventEmitter = new EventEmitter();

Once an EventEmitter instance is created, we will see what all can we do with it. Another important aspect of Event Emitters is the process of publishing Events and listening to them. As mentioned above, there is an EventEmitter class. This class comes with a lot of member functions that are used to publish events and listen to them

There are various member functions in the EventEmitter class however, the most important ones with respect to this blog are on () and emit (). The on () function is used to listen to an event whereas the emit () function is used to publish an event.

Events in EventEmitters are published and listened by a name. In the last code we wrote, an EventEmitter object was created. Let’s write another code where we raise events and listen to them.

The code for listening to an event will look like -

  • eventEmitter.on(‘myEvent’,() => {
  • console.log (‘Execution is Successful’);});

Similarly, the code for publishing an event will be –

  • eventEmitter.emit(‘myEvent’);

If the code above is run along with the snippet of creating an instance of eventEmitter, the output on the console will be – Execution is Successful.

If you look at the code carefully, an event by the name myEvent is raised. The last snippet shows that there is a listener registered for the event just above the line of the publishing event. One important thing to note is that there has to be an EvenEmittter listener to listen to the published event at the time of publishing an event.

The code above was an easy example of how the EvenEmitter class works in real life. It is time we move to some advance concepts of EventEmitter.

One important point to consider is that the EventEmitter Instance should always be Singleton for a single event name. Basically, the on () and emit () functions should always be called on the same instance of EventEmitter. If this is not followed, the listeners won’t work. Hence, you cannot register on a separate EventEmitter instance. For example, if two separate instances are used in a code for registering the publisher and for listening to the event then nothing will be printed on the console.

With this, we come to our next point where we talk about how to maintain a single Event-Emitter instance in the entire Application. The issue crops up because it is difficult to maintain a single copy of the Eventmitter instance in the whole application as usually there are hundreds of files in a single Nodejs application.

However, one can follow simple strategies to create and maintain a single copy for an EventEmitter instance. One tip to follow is that when the EventEmitter instance is being created, the storage can be done as an application-level setting using the app.set(,).

Another important question often asked is whether an Event Emitter is Synchronous or not. The simple answer to this question is that the event emitters raise events and these are synchronously executed by the listeners in the iteration of the current event loop.

With this, we come to our next topic where we understand the order of Execution of Listeners. The concept is simple: the execution of listeners is in line with the creation of listeners for an event emitter. Take a look at the code snippet to understand the order of execution of listeners.

  • import { EventEmitter } from 'events';
  • const eventEmitter = new EventEmitter();
  • eventEmitter.on('konfinityEvent', (data) => {
  • console.log (data, '- A);
  • });
  • console.log ('Statement ONE');
  • eventEmitter.on("konfinityEvent", data => {
  • console.log (data, '- B);
  • });
  • eventEmitter.emit('konfinityEvent', 'Emitted Statement');
  • console.log ("Statement TWO");

The output of this code on the console is-

  • >Statement ONE
  • >Emitted Statement – A
  • >Emitted Statement – B
  • >Statement TWO

We observed in the code above that the listeners that are registered first also get executed first.

Now that we have looked at the concept as well as the internal workings of EventEmitters in Nodejs, it’s time we look at the uses Event Emitters in Nodejs. Event emitters are widely used internally in the Nodejs environment. For example, streams are a usage of event emitters. They extend event emitters and are built on top of them that raise predefined events. Listeners are called internally by NodeJS and there is no need to call them explicitly. NodeJS internally extends event emitters, exposes the predefined events and raises these events automatically when required for streams. Nodejs reads the file as a buffer instead of reading the text content and hence the buffer gets printed instead of the string in the data listener.

Another area where NodeJS event emitters are used is the global process variable. The process exposes the variables that we can listen to as well as respond accordingly. The events are process.on(‘exit’) and process.on(‘uncaughtException’). The code below shows the usage of process variables.

  • process.on("exit", () => console.log("This is Exit"));
  • process.on("beforeExit", () => console.log("This is Before Exit"));process.on('uncaughtException', () => {
  • console.log ('This is an Exception');
  • process.exit();
  • }); throw new Error ('This is a Test Error');

The output of the code above on the console is -

This is an Exception

This is an Exit

In segments below, we will look at some of the most useful member functions of the EventEmitter class. We have looked at the on () and the emit () function earlier but there are a host of other member functions available in this class also. Let’s look at some of them in brief.

Some of the important member functions present in the EventEmitter class are – addListener(), once(), off(), removeAllListeners() etc. Let’s discuss some of the most important and popular ones.

One important member function of the EventEmitter is once (). This function will discard the listener after listening to an event. The once () function will trigger the function only once.

Another function is eventNames () which basically produces a list of all the active event names. One important thing to note is that this function does not include a function name is not included once an event gets triggered.

We studied the on () function, the addListener() is exactly the same. It’s an alias for event.on().

There are two functions, removeListener() and removeAllListeners(). The first one is used to remove a particular listener; it is done by passing the same function reference in the second parameter that was passed when creating a listener. The second function, removeAllListeners() is used to remove all active event listeners from an instance of EventEmitter.

With this, we have discussed the event emitters in NodeJS where we have covered all the important topics of this particular blog. If you have doubts or queries regarding even emitters is Nodejs, please feel free to contact us.

Also, if you want to learn web development and start your journey as a successful web developer, we highly recommend you to take on a professional web development course. A good course will not only enhance your skills but will also help in making a successful career in technology as a web developer.

Out of the many available, the course that we recommend would be Konfinity’s Web Development Course The course is well-researched and is one of the most beneficial training courses out there. It is developed by experts from IIT DELHI in collaboration with tech companies like Google, Amazon and Microsoft. It is trusted by students and graduates from IIT, DTU, NIT, Amity, DU and more.

We encourage technocrats like you to join the course to master the art of creating web applications by learning the latest technologies, right from basic HTML to advanced and dynamic websites, in just a span of a few months.

Konfinity is a great platform for launching a lucrative tech career. We will get you started by helping you get placed in a high paying job. One amazing thing about our course is that no prior coding experience is required to take up our courses. Start your free trial here.

Chat with us