Creating web servers with Node JS

Install Node JS on CentOS

1) sudo curl --silent --location https://rpm.nodesource.com/setup_4.x | bash -
2) sudo yum install -y nodejs   (CentOS)
     sudo apt-get install nodejs  (Ubuntu)

Creating Web Server

Node JS is ideal for creating scalable and lightweight web servers that can handle great number of simultaneous requests.

Node JS is shipped with several core modules out of the box and the http module is used to create http server.

Below are the steps to create a simple web server

Create a file named server.js and add the following

#require / import http module
var http = require('http');

#define a port to listen to
const port = 8080;

#define a function for listening to requests and respond with response
function handleRequest(request, response) {
      response.end('Hello World!'+ request.url);
}

#create the server
var server = http.createServer(httpRequest);

#start the server
server.listen(PORT, function()) {
       #register callback when server successfully listens
       console.log("Server listening on:  %s\n",PORT);
}

Then start the server using the node command  - node server.js

Then from web browser connect to the web server - http://<ip-of-node>:8080
Hello World!

Adding Differential behavior using Dispatchers

E.g Server should respond differently to different URL paths.  This can be achieved by adding dispatchers.

the first step is to install a http dispatcher and then import it

sudo npm install httpdispatcher

Note: npm is nodejs package manager and can be installed using yum.

var dispatcher = require('httpdispatcher');

modify the handleRequest function using the dispatcher as

function handleRequest(request, response){
    try {
       console.log(request.url);
       dispatcher.dispatch(request, response);
    } catch (err) {
       console.log(err);
    }
}



Comments

Popular posts from this blog

Amazon Scenario Questions

Using ssh keys to login to VMs

Accessing NATted VMs from Host machine using Port Forwarding