Event Loop and Event Emitters in NodeJS

 


      Previously we have seen the thread structure of NodeJS. We saw that there is a single thread which handles client connection and passes on heavy tasks to child threads. In this article we will see how to interact with those threads.

Event Loop
Recapitulate how the concept of threads was used to explain the multi-threaded nature of NodeJS.

“There is a bakery in which customers come and give order to you. You pass on the baking of cakes to different ovens according to their availability. Once a cake is ready you serve it back to the customer who requested it”

In this example, you handle the creation of threads and other process management tasks. In NodeJS terminology, you are the Event Loop. An event loop is a thread which keeps running in background and checks for any other threads which might have been pending. 

In other languages like Ruby on Rails or Django where the server is multithreaded to the client, what happens is that there is no main thread. The whole server is split into many threads but nothing sort of Event Loop.  Imagine it like you go to a bakery, place an order, the shopkeeper with his many ovens, instead of cooking a cake as whole, divides the cake into some parts and bakes them separately and then joins them together to form the complete cake. Although baking a cake may become faster, but he handles only one customer at a time which results in other customers waiting for their turn. 

This is completely opposite of Non-Blocking I/O of NodeJS. This is the reason why NodeJS can handle much larger concurrent connections. It is evident from the following statistics

Source: hashrocket.com
The graph shows the maximum number of concurrent connections that a server built with different technologies can handle. 

Events
      Again let us go back to the NodeJS bakery. We have the clients, event loop and the threads. But did you think of how will you know when a cake is ready? The answer is simple… The oven beeps and alarm or so. Right? This alarm or the sound that the oven makes when the cake is baked is called event in NodeJS.

Events are some signal which tell the main thread that a thread has finished executing and is ready with the result. Events are extensively used in NodeJS due to its non-blocking architecture. All the network interfaces and database management modules emit some sort of event to interact with the main thread.

Now let us create some events.

Create server.js file with the following contents

use strict;

const events = require(events);
const emitter = new events.EventEmitter();
let sayHelloListener = function(){
    console.log(Hello World);
};
emitter.addListener(greet, sayHelloListener);
emitter.emit(greet);

As usual, we need to import the events module to use events. For emitting events we would use the EventEmitter class of events module. We then define a listener. A listener is a piece of code which is executed whenever an event has occurred. That means that whenever the event loop hears the greet event, the sayHelloListener() will be executed. Finally we emit the greet event. You should see something like this

NOTE: Once the event is emitted and executed, the event loop still keeps listening for these events until you remove the listener.

This example shows usage of event in the main thread. Now let us see events from another thread. For this we will use setTimeout() function to execute a function in another thread.


use strict;

const events = require(events);
const emitter = new events.EventEmitter();

let sayHelloListener = function(){
    console.log(Hello World);
};

emitter.addListener(greet, sayHelloListener);

setTimeout(function(){
  emitter.emit('greet');
}, 5000);

console.log(End of script);

Here we emit the event greet in another thread which will initially be paused for 5 seconds.
Initially the output will be


Observe that the program has not exited as the event loop detected that some thread is still executing. Hence the event loop keeps waiting for the thread to finish instead of exiting.

After 5 seconds, the output becomes


This is concept of events. There are various applications of events which you will see in next articles.


No comments:
Write comments

Popular Posts

Find us on Facebook