Home » Software Development » Event Emitter in node.js

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.Currently he is engaged in providing solutions for digital asset management in media companies.He is also founder and main author of "Technical Blogs(Blog about small technical Know hows)" Hyperlink - http://www.phloxblog.in

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*


Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.