Node JS Events Module and EventEmitter

Filed Under: Node.js

We have already discussed in previous posts about Node JS Architecture. Node JS follows Event Driven Single Thread Approach. Please go through my previous posts: “Node JS Single Threaded Event Loop Architecture” and “Node JS FileSystem IO Package” because we are going to use FS module knowledge in this Events module examples.

We will discuss Node JS Platform “events” module and EventEmitter class with some suitable examples in this post.

Node JS Events Module

Node JS Platform follows Events Driven Programming model. It follows Observer Design Pattern to handle events. In Node JS applications, every operation generates an event. And it has some Event Handlers to handle those events.

For example:-
Take Node JS FS(File System) Module. When Node JS application try to open a file, then it generates an event. If it finishes reading data from a file using ReadStream, then it generates another event. If it finishes writing data to a file using WriteStream, then it generates another event. Like this for every action in Node JS Application, it generates an event.

Then, Who is responsible to generate those events? Who is responsible to handle those events? We will discuss all these questions in details soon in this post.

Like some Node modules for example “npm”, “fs” etc., Node JS “events” module is also part of basic Node JS Platform. We don’t need to do anything to setup Node JS Events module.

Why Node JS is faster?
Compared to other technologies, Node JS applications provide very high performance because of this Event-Driven Programming model.

What is EventEmitter?
As of today, Node JS “events” module has one and only one class to handle events: EventEmitter class. It contains all required functions to take care of generating events.

Who is responsible to generate events in Node JS Application ?
EventEmitter class is responsible to generate events. Generating events is also known as Emitting. That’s why this class name is EventEmitter as it emits events in Node JS Platform.

After generating events, it places all events into Event Queue(Refer “Node JS Single Threaded Event Loop Architecture” posts about the usage of Event Queue). Then Event Loop picks-up events one by one from Event Queue and process them accordingly.

Who is responsible to handle events in Node JS Application ?
Node JS Platform uses the following two components to take of events.

  • EventEmitter class
  • Java Script Callback functions

EventEmitter class is responsible to generate events and Java Script Callback functions are responsible to handle them.

We can explain this complete process with a diagram as shown below:

nodejs-event-driven-programming

  • When Node JS application starts or ends an operation, EventEmitter class generates events and places them into Event Queue.
  • Event Queue maintains a Queue of Events.
  • Event Loop continuously waits for new events in Event Queue. When it finds events in Event Queue, it pulls them and try to process them. If they require IO Blocking operations or long waiting tasks, then assigns respective Event Handlers to handle them.
  • Event Handlers are JavaScript Asynchronous Callback Functions. They are responsible to handle events and return results to Event Loop.
  • Event Loop will prepare results and send them back to the Client.

First and foremost thing to start Node JS Events programming is that import “events” module as shown below:


var events = require("events");

Then use this events variable and create an object of EventEmitter class as shown below:


var eventsEmitter = new events.EventEmitter();

EventEmitter “emit()” function

EventEmitter class has a “emit()” function, which is used to create an Event. It takes one parameter.


eventsEmitter.emit(NameOfEventToCreate);

Here, NameOfEventToCreate: we need to pass Event Name to emit() function call as String to create that Event.

Example:-


var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon");

EventEmitter “on()” function

EventEmitter class has a “on()” function, which is used to bind an Event with an Event Handler JavaScript Function. It takes two parameters.


eventsEmitter.on(NameOfEventToBind, EventHandlerFuction);

Here, NameOfEventToBind: We need to pass Event Name a to on() function call as String to bind that event to given Event Handler JavaScript Function.
and EventHandlerFuction: Given Event Handler JavaScript Function to handle that event. It may be an anonymous JavaScript function or Plain JavaScript function.

Example:-
This example is using anonymous JavaScript function as Event Handler.


var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon",function(data){
          console.log(data);
});
eventsEmitter.emit("mobileon");

We can also use Plain JavaScript function as Event Handler as shown below:


var events = require("events");
var eventsEmitter = new events.EventEmitter();
eventsEmitter.emit("mobileon",mobileOnHadler);
eventsEmitter.emit("mobileon");

function mobileOnHadler(data){
    console.log(data);
}

With this knowledge about EventEmitter class, we will develop a real-time simple example to see how Node JS handles events.

Node JS Events Example:-

This example demonstrates How to raise Events while Reading a File form FileSyste in Node JS Platform.

  • Create Node JS Project using Enide 2014 Studio IDE
  • Copy from my previous example or Create package.json file and modify it with the following content
  • package.json

    
    {
      "name": "events",
      "version": "1.0.0",
      "description": "events example",
      "main": "events",
      "author": "JournalDEV",
      "engines":{
      	"node":"*"
      	}
      }
    
  • Create a text file “JournalDEV.txt” with the following content. We are going to use this file to test Node Js events.
  • JournalDEV.txt

    
    Dear, JournalDEV Readers. 
    Thank You for your support.
    
  • Create a JavaScript file with the following content
  • events.js

    
    /**
     * JournalDEV  
     * Nodes Events Demo
     */
    var events = require("events");
    var fs = require('fs');
    var eventsEmitter = new events.EventEmitter();
    
    eventsEmitter.on('read',readFileContent);
    eventsEmitter.on('display',displayFileContent);
    eventsEmitter.on('finished',finished);
    eventsEmitter.emit('read','JournalDEV.txt');
    
    
    function readFileContent(fileName){
        console.log("Reading " + fileName + " file started:");
        fs.readFile(fileName, 'utf8', readFile);
    }
    
    function  displayFileContent(data){
        console.log("File Data:");
        console.log(data);
        eventsEmitter.emit('finished');
    }
    
    function finished(){
      console.log("Reading and Printing File content job is done successfully.");
    }
    
    function readFile(err,data,fileName) {
        console.log("Reading " + fileName + " file done successfully.");
        eventsEmitter.emit('display',data);
    }
    

    Code exaplanation:

    1. At line no:5-6, we have imported Node JS “events” and “fs” (FileSystem) module into our application cache.
    2. At line no:7, we have created an object of EventEmitter class
    3. At line no:15-33, we have written JavaScript functions. We use them as Event Handler Functions.
    4. At line no:9, we have binded “read” event with “readFileContent” Event Handler function using on() method of EventEmitter class.
    5. At line no:10, we have binded “display” event with “displayFileContent” Event Handler function using on() method of EventEmitter class.
    6. At line no:11, we have binded “finished” event with “finished” Event Handler function using on() method of EventEmitter class.
    7. At line no:12, we have raised a “read” event by passing filename “JournalDEV.txt” as input using emit() method of EventEmitter class.
  • Final Project structure will looks like this:
  • nodejs-events-project

    NOTE:-Please ignore “events2.js” file. That is back file for my future reference.

  • Run this JavaScript file and observe the output at Enide 2014 Studio IDE Console
  • nodejs-events-output

    By observing this output, we are successfully raised some events while reading a file and handled them propertly.

That’s it about Node JS Events Module. If you have any questions,please drop me a comment.

Comments

  1. Arun says:

    In this, i have a small doubt

    As you said in this post, Event loop will assign the events to the event handler, if it is a IO Blocking Operations right. In the example you have given, events you have created is not having IO Operations. So will the event loop assign the events to event handler or we will get any exceptions?

  2. Jesus says:

    what do you think of programming with only events in Node.js? I mean, no callbacks or promises, only events

  3. Shahab says:

    Hi Rambabu,
    Thanks for your great posts about NodeJs.I think under “on()” function section, second code(using plain function), line 3 is “on()” function but it is written with “emit” function.

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages