Search This Blog

Monday, October 9, 2017

Event Emitter

Many objects in a Node emit events for example, a net.Server emits an event each time a peer connects to it, an fs.readStream emits an event when the file is opened. All objects which emit events are the instances of events.EventEmitter.                
     
The event emitter allows us to decouple the producers and consumers of events using a standard interface.

EventEmitter class lies in the events module. EventEmitter provides multiple properties like on and emiton property is used to bind a function with the event and emit is used to fire an event.

var http = require("http");
var events = require('events');
var eventEmitter = new events.EventEmitter();

var serviceDownAlert = function(){
  console.log('The Ping Client --> xxx.xxx.xxx.xxx is not responding..');
}

//attach listener
eventEmitter.on('serviceDown', serviceDownAlert);

function pingClient(){
  var _host="35.185.129.118",
  _path="/isalive.html",_port="5432";
 
  httpGet(_host,_port,_path,function (err,res){
    console.log("Pinging..");
    console.log(res);
    if(res.statusCode.toString() != "200"){
      eventEmitter.emit('serviceDown');
    }
  });
}

function httpGet(host,port,path,callback){
  var options = {
    "method": "GET",
    "hostname": host,
    "port": port,
    "path": path,
    "headers": {
      "cache-control": "no-cache"
    }
  };
    var req = http.request(options, function (res) {
    var chunks = [];
    var result =
    res.on("data", function (chunk) {
      chunks.push(chunk);
    });
   
    res.on("end", function () {
      var body = Buffer.concat(chunks);
      result = {"response":body.toString(),"statusCode":res.statusCode};
      callback(null,result);
    });

    res.on('error', function (err) {
      result = {"response":null,"statusCode":res.statusCode};
      callback(err, result);
    });
  }).on('error', function(err) {
    result = {"response":null,"statusCode":"-1"};
    callback(err, result);
});
req.end();
}
//start ping client
pingClient();

Here a Ping-Client hits a server URL and expects HTTP 200 status code in response, if it doesn’t receives 200 http status code it emits “serviceDown” event.
serviceDownAlert” function is registered as event listener, after “serviceDown” event is emitted listeners get called.

We can attach multiple event listener functions to a single event even a anonymous function can also be attached as listener function to an event.
Anonymous function as Event Listener:

eventEmitter.on('serviceDown', function()
{
    console.log('Anonymous Fuction as Event Listener:: The Ping Client --> xxx.xxx.xxx.xxx is not responding..');
}

Methods of EventEmitter class:
1.       emitter.addListener(event, listener):Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added.

2.       emitter.on(event, listener):Adds a listener to the end of the listeners array for the specified event. No checks are made to see if the listener has already been added. It can also be called as an alias of emitter.addListener()

3.       emitter.once(event, listener):Adds a one time listener for the event. This listener is invoked only the next time the event is fired, after which it is removed.

4.       emitter.removeListener(event, listener):Removes a listener from the listener array for the specified event. Caution: changes array indices in the listener array behind the listener.

5.       emitter.removeAllListeners([event]):Removes all listeners, or those of the specified event.

6.       emitter.setMaxListeners(n):By default EventEmitters will print a warning if more than 10 listeners are added for a particular event.

7.       emitter.getMaxListeners():Returns the current maximum listener value for the emitter which is either set by emitter.setMaxListeners(n) or defaults to EventEmitter.defaultMaxListeners.

8.       emitter.listeners(event):Returns a copy of the array of listeners for the specified event.

9.       emitter.emit(event[, arg1][, arg2][, ...]):Raise the specified events with the supplied arguments.

10.    emitter.listenerCount(type): Returns the number of listeners listening to the type of event.

References        


No comments:

Post a Comment