#
EventEmitter object
This tutorial explains to you the EventEmitter Object and also provides you with an example.
When we are writing code many times we need to define events and function of these events to do something automatically. For instance, when an error happens, we need to log that error, or when an employee is hired an email needs to be sent to her/him.
In Node.js this can be done by defining events and do something when an event is rising. We need also to define listeners which listen the events and do something when an event occurs.
EventEmitter object in Node.js plays this role. Let's take a look at the following code:
var emitter = require('events').EventEmitter;
var em = new emitter();
console.log(' ');
//Subscribe FirstEvent - 1st method
em.addListener('FirstEvent', function (data) {
console.log('1st subscriber/FirstEvent --> ' + data);
});
//Subscribe FirstEvent - 2nd method
em.on('FirstEvent', function (data) {
console.log('2nd subscriber/FirstEvent --> ' + data);
});
// Emit FirstEvent
em.emit('FirstEvent', 'Data from FirstEvent.');
// Raising SecondEvent - without Listeners
em.emit('SecondEvent', 'Data from SecondEvent.');
//Count the number of Listeners related to the FirstEvent
console.log(em.listenerCount('FirstEvent'));
//Count the number of Listeners related to the SecondEvent
console.log(em.listenerCount('SecondEvent'));
When you run this code you will see:
NOTES:
- there are 2 listeners defined in 2 ways for the FirstEvent;
- there is no listener defined for the SecondEvent;
- we can emit the SecondEvent, but nothing is done because is no listener on this event;
- these are user-defined events, but there are also built-in events like creating a session to the server, opening a file, etc;
- listenerCount is used to see how many listeners are created on an event.