As we all know Node.js is a single threaded application in which we will heavily use event and callback. Events modules allows you to emits and handle events. In node.js there are n number of in-built modules that has the ability to emit or broadcast an event.
For example:In node.js we have file module(fs) which emits an event named 'data' every time data is read from the stream.The objects that emit events are referred to as event emitters in Node terminology.
var fs = require('fs'); // get the fs module
var readStream = fs.createReadStream('/etc/passwd');
readStream.on('data', function(data) {
console.log(data);
});
readStream.on('end', function() {
console.log('file ended');
});
When event will complete that will manage using callback.
In node.js we will handle events by using 2 types of entities: event emitter and event listener.
The step by step implementation of event example is as follow:
Step 1:In step 1 we will install the event module and initialize the event package.
var EventEmitterVar = require('events').EventEmitter,
util = require('util');
Step 2:Now for a class to have the Event emitting functionality, we need to inherit that for the class, which is done in below source code –
var exampleEventEmitterClass = function() {
console.log("The Class Constructor Example");
}
util.inherits(exampleEventEmitterClass, EventEmitterVar);
Step 3:
util.inherits will set up the prototype chain so that the EventEmitterVar prototype methods will be available in exampleEventEmitterClass instances.
exampleEventEmitterClass.prototype.emitMethod = function() {
console.log('before the emitevent');
this.emit('emittedevent');
console.log('after the emitevent');
}
Here we are emitting an event named “emittedevent”.
Now clients of exampleEventEmitterClass instances can listen to “emittedevent” event like this:
var evtEmitInstance = new exampleEventEmitterClass();
evtEmitInstance.on('emittedevent', function() {
console.log('We have got the functionality of Event Emitter');
});
Here we have got the custom event from the class and work within the event.
Now if we call the method –
evtEmitInstance.emitMethod();
the emittedEvent will be invoked.
This way we will use Event in node.js.
0 Comment(s)