Saturday, October 13, 2018

NodeJs Example

                              NodeJs Example 

The best way to learn any programming language is to start with an example program. Following NodeJs program implements a web server which returns a string to the client. A client can we a web browser or a http request from curl or any other way.



http = require('http');
var httpServer = http.createServer();
var httpServerPort = 8080;
httpServer.on('request',function (request, response) {
console.log(" Http Request Is Received");
response.setHeader('Content-Type', 'application/json');
response.writeHead(200);
response.write('Http Response is success');
response.end();
});
httpServer.on('listening', function(){
console.log('Server is Listening Now ');
});
httpServer.listen(httpServerPort);
console.log("HttpSever is running on port = " + httpServerPort);



Now Start the server with command line interface.


[root@CentOS nodeExample]# node server.js
HttpSever is running on port = 8080
Server is Listening Now

Now the HTTP server is running on port 8080 and waiting for a request from a http client. The address of linux centos machine is local to the LAN and the ip address is 192.168.1.160. Open the web browser and type the http://192.168.1.160:8080/ in address bar.  You will see the response "Http Response is success".


Program analysis:

We have successfully created a basic web server. But it is not complete until we know the meaning of each line of this program.


http = require('http'):

A program consists of functions, some functions defined by the developer and other functions defined in an external library (already developed functions by other developers). The external library in nodejs is called module. To use functions of a module it has to include in program. The require('http') function call includes the htpp module. On let site of the call http is the variable which is the reference to call a http module function.

var httpServer = http.createServer():


This do the following:
  • Creates a variable httpServer 
  • Creates HTTP server using http module. 
  • Assign created server reference in httpServer. Now all server related functions can accessed from httpServer variable.

httpServer.on('request',function (request, response) :

As node js is a single process platform which achieves parallel processing by using call backs. If we do not use callback functions, then at a single time only one request will be processed. A call bck is called when an event triggered. This lines defines a call back function for http request event received from http client. The function parameters are request and response variable.
The next lines in the function set the http response type and content type using response variable. After setting response,  writes response back to the client.


httpServer.on('listening', function()

This line sets the call back function for listening event for http server.

httpServer.listen(httpServerPort):

Set the http server on which http a http request will be received.


Error Handling In Node Js:

Till now we have created a program which assumes that every this will be correct during execution of the code. But in real world, errors are common. So the above code is incomplete without error handling. Node js is event driven system , it generates an error events upon an error. So like other event a call back function needs to define for error handling. Following is the call back which handles the error events for http server.

httpServer.on('error', function (err) { console.log(err); });

With above code whenever there is error on http server , this function will be called and error message will be printed. One error is that the port used by server is in already in use.












1 comment:

install node js npm linux

                    How to install NodeJs and NPM on Linux ? Before using a node js program. It has to be installed on a operating sys...