EventEmitter module in Node.js

NodeJs is capable of handling events. In fact many node modules such as fs.readstream emits event when it is done with reading file. You can also avail the benefits of events and program it by using EventEmitter module of NodeJs.

In this tutorial I am going to explain you some scenario’s with sample source code and graphics about event driven programming in nodejs.

What is EventEmitter?

It is a node module which allows programmer to add event listener and to emit the events. Where,

  • Event listener : It waits for event to occur such as “start”.
  • emitter : It broadcast the event for particular listener.

Syntax:

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();

Uses:

emitter.on(‘name_of_event’,function(arg..){
         // rest of code
});
emitter.emit(‘name_of_event’);

Example:

emitter.on(‘boot’,function(){
    console.log(“hello world !);
});
emitter.emit(‘boot’); //this will activate the boot listener

Our example code :

I am going to develop one node program which will read the file from file system, print it on console and terminate. This program will work as follows:

  • Emit event to start reading file.
  • Start reading and emit event when done.
  • Start printing content of file when reading is done and emit event as done.
  • if any error emit event ‘error’.
  • At ‘done’ event, assume the operation is over.

Screenshot from 2014-11-21 11:31:55

var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();
var fs = require('fs');

emitter.on('start_read',function(file_name){
      console.log("Started Reading file....nn");
      fs.readFile(file_name, 'utf8', function (err,data) {
        if (err) {
          emitter.emit('error','from_read');
        }
        else{
            console.log("Done Reading file....nn");
            emitter.emit('print_content',data);
          }
  });

});

emitter.on('print_content',function(data){
      console.log("Printing content of file....nn");
      console.log(data);
      emitter.emit('done');

});

emitter.on('error',function(type){

      console.log("Faced error while "+type);
      emitter.emit('done');

});

emitter.on('done',function(){

      console.log("Ok its done !");

});


emitter.emit('start_read','/etc/hosts');

Save the program in any file and run it using node. Expected output should be like this.abc

.on and .once :

.on is the event listener which invoke on capturing the particular event while .once invokes at first time when event is triggered and it will be only invoked when that particular event is removed and emit again.

removeListener and removeAllListeners :

After completion of particular task, you can remove the listener for that event using removeListener.
example code :

emitter.removeListener('print_content',function(){
});
//this will remove the listener for print_content event.
emitter.removeAllListeners('start_read');
//All the listener waiting for this event will be removed

Further reading:

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126