Skip to main content

An basic HTTP server for displaying static file contents in Node.js

Hello all,

In the last post, i have explained the TCP chat server.

In this post, i am going to briefly explain how to create a basic http server and extend it to create a HTTP server that can be used to display the contents of stored static files.

The code for final static file HTTP server will be at last of tutorial,so in between tutoria. dont worry about the code.

So to create an http server, we need to use core "http" node module.
 var http = require("http");

 then server is created by function createServer with a callback (called everytime a request is raised for server [similar as in TCP])

here the callback has two parameters, request and response. request attribute holds information related to information in request like url, headers etc..

var server = http.createServer(function(request,response){
   ...
});

to write a response to a browser, we have response attribute.
var server = http.createServer(function(request,response){
     response.writeHead(200 , {"Content-type":"text/plain"})
     response.end("hello from HTTP server");
});

Here the writeHead function is called on response object, used to set resposne header.
200 : Success status (like 404 : page not found. 403 Forbidden etc..)
The next parameter sets the page content-type.

At the end we need to listen to the some port.

server.listen(port);


So , a basic HTTP Server looks like,(http_server.js)
  var http = require("http");
var port = 1234;
var server = http.createServer(function(request,response){
    response.writeHead(200,{"Content-type":"text/plain"});
    response.end("hello from Http Server");
});

server.listen(port);


To run this, run http_server.js

open browser and run http://localhost:1234

And thats it. This is the first basic HTTP web server.

HTTP Static File  Server

For this server, you need the knowledge of fs, path and  http node modules.

The code for this is below,

var fs = require("fs");
var http = require("http");
var path = require("path");
var port = 1244;
var server = http.createServer(function(request,response){
    console.log("TRrying to read file "+request.url);
    var new_url = path.normalize("."+request.url);
    console.log(new_url);
   
    function reportError(err){
        console.log(err);
        response.writeHead(500);
        response.end("Internal server error occured.");
    }
   
    function fileNotFound(){
        response.writeHead(404);
        response.end("Requested file does not exixts.");
    }
   
    function forbiddenError(){
        response.writeHead(403);
        response.end("Access is forbidden.");
    }
    fs.exists(new_url,function(exists){
        if(exists)
        {
            fs.stat(new_url,function(err,stat){
            if(err){
                console.log("An error occured");
                return reportError(err);
            }
            else
            {
                if(stat.isDirectory()){
                    console.log("Requested file is directory")
                    return forbiddenError();
                }
                else
                {
                    console.log("Requested file found");
                    var rs = fs.createReadStream(new_url);
                    response.writeHead(200);
                    rs.pipe(response);
                }
            }
           
            });
        }
        else
        {
            return fileNotFound();
        }
    });
   
});
server.listen(port);

If anyone have any doubt regarding the code, feel free to comment.

Thanks.

Comments

Popular posts from this blog

Login with Google Account using PHP / Javascript using OAuth2.0

Login with Google Account using PHP with code This post have Complete Code for Login / Sign-in  with google Account  using PHP / Javascript with oAuth2.0 Basically today we have seen almost every website needs you to register yourself before you can post or take part in any discussions to the website. But it become a tedious task to register and login to many different sites. Solution is to provide the users the option to Login with existing Google / Facebook account as almost everyone have Facebook and Google account.. In this post, I am going to explain how to integrate the Google Login / Sign in  for your website. For this,  First you need to create your Client ID, Client Secret and your developer API key. For this go to https://developers.google.com/identity/sign-in/web/sign-in Click on the button Create Project. A new window will open up. Please select Create Project / or select already created Project. It will then ask for about type of Project. Please

How To Set Up Apache Virtual Hosts on Ubuntu

How to setup Virtual Host in Ubuntu 16 / Ubuntu 18 on localhost / local machine To run the website with host on localhost(With LAMP) becomes important in many cases. This blog post will demonstrate how to achieve this. Assuming you have LAMP already installed and reading the code from (/var/www/html) Follow the simple steps below Create the code base To Create the code, simply create a directory named localweb inside /var/www/html. Create a file index.php inside localweb directory Content of index.php file <?php  echo "Local Website"; ?> Now our code base is set, so we need to configure apache Go to apache directory cd  /etc/apache2/sites-available/ Create one file named localweb.conf with content <Directory /var/www/html/localweb/>     AllowOverride All </Directory> <VirtualHost *:80>     ServerAdmin admin@localweb.com     ServerName localweb.com     ServerAlias www.localweb.com     Documen

ORCAM - Blind can read too.!!

ORCAM: The technology that was developed mainly with the aim – to help to help the visually impaired and blind regain the functionalities that were lost. Yeah. So now even visually impaired guys can get to know even the smallest written things just by pointing towards them, like the reading the book. Yes. Even those who are completely blind, can even read a book using ORCAM. SO what actually is ORCAM.????? A visual system with human like performance to help visually impaired people Here is a look towards ORCAM-See for yourself Search Results It is a simple device with a camera and earphone   that fits in the simple glasses   and uses the Text-to-speech technology to read the objects and sends the user in the voice format with the help of the earphone. The   OrCam device is able to identify thousands of objects, including the faces of loved ones, dogs, buses, newspaper text and store signs, all with the point of the finger. Its v