Node.js

Handling Events with Node.js

The events module in Node allows you to emit and handle events. Lot of in-built modules (objects) in Node has the ability to emit or broadcast an event.

For example, the fs or File stream module emits an event named ‘data’ every time the data is read from the stream. The objects that emit events are referred to as event emitters in Node terminology.

The event, when emitted, is handled using a callback function. The below code shows handling the click event.

obj.on('click', function() {
    console.log('I am clicked');
});

The event emitter framework models on Java based Observer pattern where an observer of an event is notified every time that event occurs.

This article will show you how to emit and handle events using Node.js event API.

The Node event handling framework deals with two types of entities: event emitter and event listener. There is clear separation of roles here. Event listener registers to the event emitter for a particular event and listens for that event. It is important to note that event listeners can be many i.e. more than one listener can be registered for a particular event.

When you emit an event, you are essentially emitting an event type that is defined as string. As you can see from the above code, ‘click’ is the event type defined as string. Names of the event are user defined and one can choose the name of the event based on the action or the state of an object.

To use event handling with Node, you have to install and use events module. The below code makes use of events module to show a simple event handling

var e = new (require('events').EventEmitter)();
e.on('greet', function() {
	console.log('hello world');
});
e.emit('greet');

The above code first loads the events module and creates the EventEmitter object. It then emits event using the emit() function. The event type is ‘greet’. The on() function is used to handle ‘greet’ event by attaching an anonymous callback function as a second argument. Once the ‘greet’ event is emitted, the callback function is invoked.

There is also a special event type called as ‘error’. This event can be emitted when there is an error condition. If you choose not to handle this error event, then Node event emitter will throw and print error stack trace. The below revised code shows the ‘error’ event.

var e = new (require('events').EventEmitter)();
e.on('greet', function() {
	console.log('hello world');
});
e.on('error', function() {
	console.log('It is an error');
});
e.emit('greet');
e.emit('error');

As you can see, the ‘error’ event is handled appropriately. If you choose not to handle error event, then it will throw and display the error trace as follows:
node-error-event-trace
What this means is, you can emit any arbitrary events and choose not to handle it. The program will work just fine. But for the error event, you must handle it.

Passing parameter to callback

The event can also be handled with one or more parameter passed to the callback function. While emitting an event, you specify what data to be passed to the callback function. The below code demonstrates the same:

var e = new (require('events').EventEmitter)();
e.on('greet', function(data) {
	console.log('hello ' + data);
});
e.emit('greet', 'world');

In the above code, you pass the value ‘world’ while emitting the event. It is then handled in the callback function by passing it as an argument.

The Node event emitter API also provides the following functions:

addListener() – To add an event listener to a particular event
once() – To add an event listener to a particular event that will be invoked at most once
removeEventListener() – Removes a specific event listener for a specified event
removeAllListeners() – Removes all event listeners for a specified event

Using addListener

With addListener method you can bind a named callback function. The below code shows how a named callback is used with addListener() method.

var e = new (require('events').EventEmitter)();
function sayHello() {
	console.log('hello world');
}
e.addListener('greet', sayHello);
e.emit('greet', 'John');

In the above code, we are using sayHello named function. Though you can still use inline anonymous callback function with addListener() method, just like the on() method.

That was brief about event handing in Node. You can play around with different Node modules and check the API doc to see what events they emit and handle them accordingly.

Reference: Handling Events with Node.js from our WCG partner Rajeev Hathi at the TECH ORGAN blog.

Rajeev Hathi

Rajeev is a senior Java architect and developer. He has been designing and developing business applications for various companies (both product and services). He is co-author of the book titled 'Apache CXF Web Service Development' and shares his technical knowledge through his blog platform techorgan.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button