What is 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 corresponding event handler captures the event. No threads but node js is high in performance for concurrent processing. This is possible because of event model. In concurrent processing , two or more tasks overlap in time frame, but do not execute at same time. This involves context switching among the tasks by operating system.

The APIs in node js are non-blocking in nature. Non blocking API is the function when called from a program, the calling program does not wait to complete the API, before calling any other function or API. When non-blocking API , completes, emits an event, in event handler the task after completion can be specified. 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 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 a HTTP server. Registering http serve for events ('request' and 'listening').  Each event have a callback function also registered along with event. When a new http request is received, the request callback is call. When 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 switch is key factor in event based processing. Code executing context switch from one processing to other 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 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 User event and event handler in node js:

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

Node js provides Events module.  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 above a event first is emitted. Which is handled by its registered firstEventHandler callback. Here no argument is passed from emitter to call back. There are situations those requires passing of arguments from emitter to 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. Same number of arguments should be declared in call back function.

 

Leave a Reply

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