Event Emitter in node.js
Event emitter from one class triggers an event to which other functions from other classes can listen. Libraries offer implementations of a framework for publishing events and listening to them.
On Node many objects can emit events.
The .on method in a Event Emitter –
We can listen for these events by calling one of these objects “on” method, passing in a callback function. A file ReadStream can emit a ‚”data” event every time there is some data available to read.
The example of the code –
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'); });
Here we are binding to the readStream “data” and “end” events, passing in callback functions to handle each of these cases. When one of these events happens, the readStream will call the callback function.
There are 2 ways of doing the above operation –
- Pass in an anonymous function
- Pass a function name for a function available on the current scope, or a variable containing the function.
The .once method –
When we want the callback method to be called only once, we use this in our work –
server.once('connection', function (stream) { console.log('We have our first call!'); });
To remove all Listeners from the current context we should use removeAllListeners function.
Creating a Event Emitter –
We have to use the “events” package in node.js.
To install event package, we need to execute –
npm install events
in node.js environment.
To initialize the Event package, we need to write –
var EventEmitterVar = require('events').EventEmitter, util = require('util');
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);
util.inherits will set up the prototype chain so that the EventEmitterVar prototype methods will be available in exampleEventEmitterClass instances.
This way instances of exampleEventEmitterClass can emit events:
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.
The above is a short introduction of Event Emitter in node.js. We will write more on this in later posts.