About Piyas De

Piyas is Sun Microsystems certified Enterprise Architect with 10+ years of professional IT experience in various areas such as Architecture Definition, Define Enterprise Application, Client-server/e-business solutions.

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 -

  1. Pass in an anonymous function
  2. 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.
 

Reference: Event Emitter in node.js from our JCG partner Piyas De at the Phlox Blog blog.
Related Whitepaper:

Software Architecture

This guide will introduce you to the world of Software Architecture!

This 162 page guide will cover topics within the field of software architecture including: software architecture as a solution balancing the concerns of different stakeholders, quality assurance, methods to describe and evaluate architectures, the influence of architecture on reuse, and the life cycle of a system and its architecture. This guide concludes with a comparison between the professions of software architect and software engineer.

Get it Now!  

Leave a Reply


8 × = forty eight



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books