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 simultaneously. 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 nonblocking API completes, it emits an event. The 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 nonblocking, the query keeps executing, and the node js loop again waits for events. When the query completes, an event is received.

Node Js HTTP Server Example:

Node js npm has a built-in HTTP module for handling HTTP communications. In the following example, the HTTP server listens on port 5060 for incoming requests and sends a response.

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 Nonblocking APIs:

Node js support Nonblocking APIs for making fully event-based concurrent processing. Context switching is a major key factor in event-driven handling. On an event, flow switches from one leg to another.

How to read a file 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

How to read a file in nonblocking mode?

This example shows a nonblocking call to the file read. In a nonblocking API, the processing continues. When the API completes, the callback function is called. There will be context switching from main to file read call back once the file read ends.

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 loop keeps waiting longer, 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 is first 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 the event emitter to the 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, multiple arguments can be passed with commas separated. The same number of arguments should be declared in the callback function.

Leave a Comment