Node JS EventEmitter Example

Node JS EventEmitter is the object which can emit event to the event loop. It is the class in node js events module. It can be used in many cases such as when http web server receive a client request will use EventEmitter to create a on receive event, when fs module open a file will use EventEmitter to create a file open event. This article will introduce EventEmitter methods and how it works with examples.

1. How To Use EventEmitter Class.

  1. Import events module, this is a Node JS built-in module. This module has only EventEmitter class.
    var events = require('events');
  2. Create EventEmitter object use events object.
    var event_emitter = new events.EventEmitter();
  3. Then you can use event_emitter to add, remove, list event listeners to related event and emit event when required.
  4. Below is an example about using EventEmitter to emit event and bind event listener. We can see that same event can bind different event listener, when the event happen the two event listener will be executed by order.
    // Include node js events module.
    var events = require('events');
    
    // Create EventEmitter object.
    var event_emitter = new events.EventEmitter();
    
    // Add first anonymous event listener function to listen open_event.
    event_emitter.on('open_event', function(error, result) {
     console.log('open_event happen.');
    });
    
    // Add second anonymous event listener function listen same event.
    event_emitter.on('open_event', function(error, result) {
     console.log('open_event happen again.');
    });
    
    // Trigger event after one second.
    setTimeout(function() {
     event_emitter.emit('open_event');
    }, 1000);

    The output is.

    open_event happen.
    open_event happen again.

2. error Event.

error is a special event defined by EventEmitter, it means an error happened. When trigger this event, Node system will print error messages in the console if you do not catch it in your code. You can create error event listener to catch the error event and add more detail error information. This can avoid Node app exit and crash. This is something like java exception.

event_emitter.on('error', function (error, result) {
    console.log("An error happened. Error message is " + error);
})

event_emitter.emit("error", "hello");

Below is output.

An error happened. Error message is hello

If you do not provide error event listener like below.

// Below trigger event code will throw error because no listener is added for error.
event_emitter.emit("error", "hello");
// Below trigger event code will not throw error even it also do not has event listener.
event_emitter.emit("open", "hello");

It will give you below error message when execute, but the open event emit action will not throw error message even though there is no listener registered to it also.

events.js:168
 throw err;
 ^

Error: Uncaught, unspecified "error" event. (hello)
 at EventEmitter.emit (events.js:166:17)
 at Object.<anonymous> (D:\Workspace\dev2qa.com-example-code\JavaScriptExampleWorkspace\NodeJSWorkspace\Event\custom-event.js:57:15)
 at Module._compile (module.js:571:32)
 at Object.Module._extensions..js (module.js:580:10)
 at Module.load (module.js:488:32)
 at tryModuleLoad (module.js:447:12)
 at Function.Module._load (module.js:439:3)
 at Module.runMain (module.js:605:10)
 at run (bootstrap_node.js:427:7)
 at startup (bootstrap_node.js:151:9)

Process finished with exit code 1

3. EventEmitter Class Methods.

  1. listenerCount(emitter, event) : Return special event emitter emitted special event’s listener count.
READ :   How To Create Custom NPM Modules

4. EventEmitter Instance Methods.

  1. addListener(event, listener) : Add a listener which listen to special event at the end of the event listener array.
  2. emit(event, [arg1], [arg2], […]) : Emit event to the event queue, then registered listener can catch and process the event. You can add any arguments in this method, all the arguments will be passed to all the registered listeners. And you can access the EventEmitter which emit the event useĀ this argument in the listener function.
  3. listeners(event) : Return special event’s listener objects in an array.
  4. on(event, listener) : Register a listener to a special event.
  5. once(event, listener) : The listener only execute once for the special event, after listener execute, it will unregister to the event.
  6. removeAllListeners([event]) : Remove all listeners registered to the event, if not specify event then remove all listeners.
  7. removeListener(event, listener) : Remove special event’s listener, the listener must has registered to the event before.
  8. setMaxListeners(n) : Set the max listener number, the default value is 10, if you add more than 10 listeners on one event, node js will output warn messages.

5. Extend EventEmitter.

In practice we do not directly use EventEmitter class, we just use it as your class’s parent class and emit events through it’s various methods.

var eventEmitter = require('events').EventEmitter;

// Define your java class extends EventEmitter class.
class CarEmitter extends eventEmitter {}

// Create an instance of your custom class.
var my_car = new CarEmitter();

// Register listener function to start event.
my_car.addListener('start', function(){
    console.log('You start the car.');
});

// Register listener function to restart event.
my_car.on('restart', function(){
    console.log('You car restart again.');
});

// Register once listener to error event.
my_car.once('error', function(){
    console.log('The car has some error.');
});

var count = eventEmitter.listenerCount(my_car, 'error');
console.log("error event listener count is " + count);

// Emit start event.
my_car.emit('start');

// Emit error event.
my_car.emit('error');

// Emit restart event.
my_car.emit('restart');

var count = eventEmitter.listenerCount(my_car, 'error');
console.log("error event listener count is " + count);

Below is the output.

error event listener count is 1
You start the car.
The car has some error.
You car restart again.
error event listener count is 0
(Visited 326 times, 1 visits today)

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.