NodeJS EventEmitter Tutorial

View more categories:

1- NodeJS EventEmitter

NodeJS supports events in applications very perfectly. Every action on a computer is an event . For example, when you read a file on hard drive. It means that you have to do two actions " open the file" and " close it" after finishing reading it, so here we have two " Open "&" Close " events. Based on events, you insert your codes to do something.
var fs = require('fs');

// Create a stream to read file
var rs = fs.createReadStream('C:/test/demo.txt');

// The event 'open':
rs.on('open', function() {
    console.log('File opened!');
});
Module events provides you with an  EventEmitter class, that is a central class in the NodeJS,  assisting in defining an event, registering Listeners of this event, and emitting (emit) the event.

Listener

In the  NodeJS, the  Listener is a function. It will be called to execute when an event occurs. Probably, 0, 1 or many Listeners are being bound to such event.
For simplicity, look at the following illustration: a mouse and a mouse trap. An event is prepared to take place. When the event occurs (the cake is stolen), the mouse trap will perform its task. The mouse trap herein is a "Listener", which will work when the event happens.

2- Example of EventEmitter

Import Events module , and declare an  EventEmitter ​​​​​​​object:
// Import events module
var events = require('events');


// Create an EventEmitter object
var eventEmitter = new events.EventEmitter();
Register  Listeners (The functions will be called to execute when an event occurs).
// Add Event Listener
eventEmitter.addListener('bellRing', bellRingHandler1);

// Add Event Listener
eventEmitter.addListener('bellRing', bellRingHandler2);
Emit the event:
// Fire bellRing event!!
eventEmitter.emit('bellRing', 'Jerry');
first-example.js
// Import events module
var events = require('events');


// Create an eventEmitter object
var eventEmitter = new events.EventEmitter();

// A Listener
var bellRingHandler1 = function bellRingHandler1(who) {
   console.log("\n");
   console.log('The Bell Ringing..... (Handler 1)');

   console.log(" " + who + " was standing behind the door!");
   if(who == 'Jerry') {
       console.log(' Tom, help me!!');
       return;
   }
   console.log(" Welcome " + who);
}

// A Listener
var bellRingHandler2 = function bellRingHandler2(who) {
   console.log("\n");
   console.log('The Bell Ringing..... (Handler 2)');

   eventEmitter.emit("nobodyIsAtHome");
}

// A Listener
var nobodyIsAtHomeHandler = function nobodyIsAtHomeHandler()  {
   console.log("\n");
   console.log(" Sorry, Nobody is at home now, Please leave your message!")
}


// Add Event Listeners
eventEmitter.addListener('bellRing', bellRingHandler1);
eventEmitter.addListener('bellRing', bellRingHandler2);

eventEmitter.addListener('nobodyIsAtHome', nobodyIsAtHomeHandler);

// ----- Testing ------

// Fire bellRing event!!
eventEmitter.emit('bellRing', 'Jerry');
Run the example:
node eventemitter-examples/first-example.js

3- EventEmitter Class

No Method Description
1 addListener(event, listener)

Add a listener the end of the listeners array for the specified event. This method doesn't check whether this listener has ever been added or not. 

2 on(event, listener)

Exactly, this method is 100% identical to the addListener method.

3 once(event, listener)

Add a listener to the listeners array of the specified event. But this listener is only called one time when an event happens. After that it is removed from the array.

4 removeListener(event, listener)

Remove a listener from the listeners array of the specified event. If a listener  has been added to this array many times. To remove this listener fully, you need to call this method many times.

5 removeAllListeners([event])

Remove all listeners, or remove all listeners of an  event designated.

6 setMaxListeners(n)

By default, EventEmitters will print a warning if more than 10 listeners are added for a particular event. This is a useful default which helps finding memory leaks. Obviously not all Emitters should be limited to 10. You can set a different number, or set to zero for unlimited.

7 listeners(event)

Return a listeners array to the specified event.

8 emit(event,
[arg1], [arg2], [...])

Executes each listener in the array in turn, with parameters. Return true if the array has at least one listener. On the contrary, return false.

View more categories: