Node js event driven architecture

What is the Node js event?


This node js tutorial explains the event-driven architecture for concurrent processing. Node Js have an Event loop architecture. When a node js program receives an API or Message, an event is emitted and the corresponding event handler captures the event.

No threads but node js do concurrent processing at a very high volume. This is possible because of the event model. In concurrent processing, two or more tasks overlap in a time frame but do not execute at the same time. This involves context switching among the tasks by the operating system.

The APIs in node js are non-blocking in nature. Nonblocking APIs are the functions when called from a program, the calling program does not need to wait to execute the API fully, before calling any other function or API. When a non-blocking API, completes, it emits an event.  event handler function can be specified along with an API call. For example, to access a database query, if the call is blocking, all processing stops, but API is non-blocking, query keeps executing and node js loop again wait for events. When the query completes, an event is received.

Node Js HTTP Server Example:

Node js npm have built in http module for handling http communications. In following example http server listen for incoming request and sends a response. The http server listens on port 5060.

http = require(‘http’);var httpServer = http.createServer();

httpServer.on(‘request’,function (request, response) {

console.log(” Http Request Is Received”);

response.setHeader(‘Content-Type’, ‘application/json’);
response.writeHead(200);
response.write(‘Http Success’);
response.end();
});

httpServer.on(‘listening’, function(){
console.log(‘Server is Listening Now’);
});

httpServer.listen(5060);

In above example creates an HTTP server. Registering HTTP serves for events (‘request’ and ‘listening’).  Each event has a callback function also registered along with the event. When a new HTTP request is received, the request callback is called. When the server starts listening, the listening event callback is called.

Blocking and Non-Blocking APIs:

Node js supports Non-Blocking APIs for making fully event-based concurrent processing. Context switching is a major key factor in event-based processing. Code does context switching from one processing to others if an event occurred.

File read in blocking mode:

This example shows a blocking call to the file read API. The disadvantage of this call is that, until API returns the result, full software processing stops as node js is single-threaded.

 const fileHandler = require('fs');
 console.log("File Reading Starts");
 const content = fileHandler.readFileSync('./testFile.txt');
 console.log("File Reading Ends");

Output on console:

[root@nodeExample]# node blockingFileRead.js
 File Reading Starts
 File Reading Ends

File read in non-blocking mode:

This example shows a non-blocking call to the file read. In a non-blocking API, the processing continues, when the API completes the callback function is called. In this, there will be context switching from main to file read call back once the file read completes.

const fileHandler = require('fs');
console.log("File Reading Starts");
fileHandler.readFile('./testFile.txt', (error, content) => {
 if (error)
 {
    console.log("Error In Reading");
 }
    console.log("File Reading Ends");
 });
console.log("Program Ends");
Output:

[root@CentOS_6_64-160 nodeExample]# node nonBlockingFileRead.js
 File Reading Starts
 Programe Ends
 File Reading Ends

Creating a User event and event handler in node js:

While developing a node js application a developer can come across a situation where a very log task can be divided into multiple smaller tasks.  If not done so, then the event look keeps waiting for a longer time and new requests may get timed out. The communication between tasks will be based on the event. There should be a way to listen to an event and emit an event.

Node js provides the Events module.  The following example shows how to register a callback for an event and emit an event. Here the event name is first.

var myEvents = require('events');
 var myEventEmitter = new myEvents.EventEmitter();
/* This is the function which will handle a event */
var firstEventHandler = function () {
 console.log('First Event Handler');
 }
/* Registering event callback function for event named first"
 myEventEmitter.on('first', firstEventHandler);
/* Emitting Event First */
 myEventEmitter.emit('first');

In the above, an event first is emitted. Which is handled by its registered firstEventHandler callback. Here no argument is passed from the emitter to call back. There are situations that require the passing of arguments from the emitter to the callback.

Passing arguments from event emitter to callback:

var myEvents = require('events');
 var myEventEmitter = new myEvents.EventEmitter();

var firstEventHandler = function (a,b,c) {
 console.log('First Event Handler');
 console.log("aggumnets" + a + b +c );
 }
 myEventEmitter.on('first', firstEventHandler);
 myEventEmitter.emit('first', 1,2,3);

While emitting an event any number of arguments can be passed with commas separated. The same number of arguments should be declared in the call-back function.

Leave a Comment