- Oct 02, 2018
- admin
- 0
NodeJS EventEmitter:
An action performed is termed as an event. Node.js is faster than other frameworks as it uses event driven programming technique. An event is more or less similar as a callback, the only difference is that the event handling works on the observer pattern while, the callback functions are called when an asynchronous function returns its result.
Node.js Events Module:
Events is a built-in module in Node.js which is used to create-, fire-, and listen an event.
Node.js EventEmitter Object:
The Node.js EventEmitter objects are used to assign event handlers to an event in two ways:
- Return EventEmitter from a function
- Extend the EventEmitter class
Syntax:
- To include the Events module:
var events = require(events);
- To bind event and event listener:
var eventEmitter = new events.EventEmitter();
- To bind event handler with an event:
eventEmitter.on (event_Name, eventHandler);
- To fire an event:
eventEmitter.emit (event_Name);
Example:
var events = require(‘events’);
var eventEmitter = new events.EventEmitter();
var Handle = function ()
{
console.log(‘I love Programming!’);
}
eventEmitter.on(‘coders’, Handle);
eventEmitter.emit(‘coders’);
OUTPUT:
I love Programming!