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

What is MonGoDB??

Share on Google Plus Now a Days, we are hearing a lot about MongoDB.

So, in this post I will try to briefly introduce to MongoDB.

MonGoDB is "Non-Relational, JSON, Document Store".

Explaining in detail,

Non-Relational, --> The DB we use most like SQl, Oracle are Relational DBs(RDBMS). They do have the fixed schemas, lots of tables. So Non-relational in nothing like that.

JSON : (JavaScript Object Notation) : It is basically a document with information in the form of key value pair.

for example,

{
   name:"lorem",
   address:"ipsum
}

thats it. 
A simple JSON document where name and address are key
and "lorem" and "ipsum" are corresponding values.

So, MongoDB is the Non Relational database which stores information using DOCUMENT and that document is a JSON document.

MongoDB stores collections of documents.
(Consider the above exxample as collection  "Person"  with a document)(will elaborate it later more)


Need of MongoDB:
The Databases we use…

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

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.

Download Source Code

Live Demo



For this,  First you need to create your Client ID, Client Secret and your developer API key.

For this go to https://code.google.com/apis/console/


Click on the button Create Project. A new window will open up like this :













Enter the Project name and submit on Create.

Wait for new seconds, the new page will open like this.



On the left menu, click on API & Auth and click on credentails. Then…

TCP Chat Server in Node.js

d.Hello all.

Today in this post, I am going to explain about how to use a "net" module in node.js and build a basic chat server.(i.e a TCP chat server)

For this, you need to use either telnet / netcat(nc).(I have tried it on netcat, simply google "netcat download")
(Dont worry about the script for now, i will upload it, just go through the tutorial to understand the concept)

So, lets begin,

first of all to use node "net" module , we need to import it in out script.

var net = require("net")

This will import the net module. Now moving ahead, we need to create a server. This is done by createServer  function(on simply Server function).

var server = net.createServer()

createServer has a callback whenever a client connects to a server.

i.e
var server = net.createServer(function(socket){

});

The code inside the createServer() function is callback(Hope you have know about the callbacks / event driven programming). This gets called whenever, a client gets c…