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.


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


         // rest of code


    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');

      console.log("Started Reading file....nn");
      fs.readFile(file_name, 'utf8', function (err,data) {
        if (err) {
            console.log("Done Reading file....nn");


      console.log("Printing content of file....nn");



      console.log("Faced error while "+type);



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



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 :

//this will remove the listener for print_content event.
//All the listener waiting for this event will be removed

Further reading:

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.