NodeJS Event Emitter: The Node.js permits you to create & handle your own custom events with the help of the events module. The Event module contains an EventEmitter class that can be used to handle custom events.
NodeJS EventEmitter Example
// get the reference of EventEmitter class of events module var events = require('events'); //create an object of EventEmitter class by using above reference var em = new events.EventEmitter(); //Subscribe for FirstEvent em.on('FirstEvent', function (data) { console.log('First subscriber: ' + data); }); // Raising FirstEvent em.emit('FirstEvent', 'This is my first Node.js event emitter example.');
Here, we have imported the “events” module and created an object in the EventEmitter class. The event handler function On() needs the event name that can handle and the callback function to call when the event is raised.
The emit() function is called for the specified events. The first parameter is the event name as a string and remaining are arguments. These arguments can be zero or more arguments for the event to be emitted. The custom event name can also provide in emit() function.
The Node.js allows you to include addListener() methods to the event. For that let’s see an example.
addListener() Method Example
var emitter = require('events').EventEmitter; var em = new emitter(); //Subscribe FirstEvent em.addListener('FirstEvent', function (data) { console.log('First subscriber: ' + data); }); //Subscribe SecondEvent em.on('SecondEvent', function (data) { console.log('First subscriber: ' + data); }); // Raising FirstEvent em.emit('FirstEvent', 'This is my first Node.js event emitter example.'); // Raising SecondEvent em.emit('SecondEvent', 'This is my second Node.js event emitter example.');
EventEmitter Class Methods List
Method | Description. |
---|---|
emitter.addListener(event, listener) | This method adds a listener to the end of the listener’s array. If the listener already includes it doesn’t specify. |
emitter.removeListener(event, listener) | This method removes the listener from the listener array for a particular event. The changes in the array specified in the listener array after the listener. |
emitter.removeAllListeners([event]) | This method removes all listeners or the specified event. |
emitter.getMaxListeners() | This method is used to return the current maximum listener value either by the emitter.serMaxListeners(n) or Eventemitter.defaultMaxListerners.(Default) |
emitter.setMaxListeners(n) | This method gives a warning if more than 10 listeners are included for a particular event. |
emitter.on(event, listener) | This method adds a listener to the end of the listener’s array. If the listener already includes it doesn’t specify. It works the same as an emitter.addListener(event, listener). |
emitter.once(event, listener) | This method adds a listener to an event only once. This listener invokes only the event fired when it is removed. |
emitter.listeners(event) | This method provides a copy of the array of listeners for the particular event. |
emitter.emit(event[, arg1][, arg2][, …]) | This method is called for particular events with arguments. |
emitter.listenerCount(type) | It provides how many listeners are listening to the event. |
EventEmitter Patterns
The two patterns that are used to bind an event with the EventEmitter class in Node JS.
- Return EventEmitter from Function.
- Extend the EventEmitter Class.
Return EventEmitter from Function
With this pattern, the constructor function returns an Eventemitter object that is used to emit events inside the function. The EventEmitter object is used to subscribe to the event.
Return EventEmitter from Function Example
var emitter = require('events').EventEmitter; function LoopProcessor(num) { var e = new emitter(); setTimeout(function () { for (var i = 1; i <= num; i++) { e.emit('BeforeProcess', i); console.log('Processing number:' + i); e.emit('AfterProcess', i); } } , 2000) return e; } var lp = LoopProcessor(3); lp.on('BeforeProcess', function (data) { console.log('About to start the process for ' + data); }); lp.on('AfterProcess', function (data) { console.log('Completed processing ' + data); });
Return EventEmitter from Function Example Output
Here, the LoopProcessor() function creates an object of EventEmitter class and used it “BeforeProcess” and “AfterProcess” events. After returning the object from EventEmitter from the function use LoopProcessor that binds the events with the on() or addListener() function.
Extend EventEmitter Class
With this pattern, the constructor function returns an Eventemitter object that is used to emit the events.
Extend EventEmitter Class Example
var emitter = require('events').EventEmitter; var util = require('util'); function LoopProcessor(num) { var me = this; setTimeout(function () { for (var i = 1; i <= num; i++) { me.emit('BeforeProcess', i); console.log('Processing number:' + i); me.emit('AfterProcess', i); } } , 2000) return this; } util.inherits(LoopProcessor, emitter) var lp = new LoopProcessor(3); lp.on('BeforeProcess', function (data) { console.log('About to start the process for ' + data); }); lp.on('AfterProcess', function (data) { console.log('Completed processing ' + data); });
Extend EventEmitter Class Example Output
Here, we extended the LoopProcessor constructor function with EventEmitter class with util.inherits() method. To handle own events use EventEMitter methods with LoopProcessor object.
That’s it, now you can handle your own custom events in NodeJS with EventEmitter Class.