kbvishnu
kbvishnu

Reputation: 15630

Basic web server issuw with Node Js

I am new to node js. I am following the link. But this always executing the response.writeHead(404); So I can't able to view the index.html http://thecodinghumanist.com/blog/archives/2011/5/6/serving-static-files-from-node-js

This is my web server node js code.

var http = require('http');
var path = require('path');
var fs = require('fs');

http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = "."+request.url;
    if (filePath == './')
        filePath =  '/index.html';
    else
        console.log(request.url);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    fs.exists( filePath, function (exists) {
        console.log(filePath);
        if (exists) {

            fs.readFile(filePath, function (error, content) {
                if (error) {
                    console.log(error);
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}).listen(8125);

My questions.

  1. This is not showing the index.html.
  2. How can i send response or html file based different requests ? eg: http://localhost:8125 -> index.html http://localhost:8125/firstpage.html -> firstpage.html
  3. Do we need to put the html files in the same directory which contains server.js (web server) ?

I also tried the same in cloud9 ide.

enter image description here

I found a similar issue in SO. but I did n't get a clear idea how to fix it. Node.js - Socket.io client file not being served by basic node web server Thanks in advance.

Upvotes: 0

Views: 259

Answers (1)

Fafhrd
Fafhrd

Reputation: 436

1- Yes, true. I can reproduce the error. I am not familiar with the tutorial, but obviously the line filePath = '/index.html'; should be filePath = './index.html';.

Otherwise the server is looking for "/index.html", i.e. a file named "index.html" at the root of your filesystem, and not in the current directory. Perhaps it is working on windows OS, but on *nix-like this will not work. I you add the ., index.html is served.

2- For this you need to import the 'url' node.js module and then you have access to a convenient way to parse URLs : http://nodejs.org/api/http.html#http_request_url Basically, before the fs.exist ... line, you can add the following:

var requestedfile = urlparser.parse(request.url).pathname;
console.log("requested URL path name : " + requestedfile);

and then you will be able to handle different requests.

3- Yes you can. Remember that when adding a dot "." before "index.html" at issue 1., you were giving a relative path to index.html (relative to where server.js is located on your filesystem). You can therefore specify any other relative path this way.

If you store your pages in another directory outside the current folder (for isntance /var/www/mysite), you can still serve these pages by concatenating a string variable containing this absolute path, with the request path name. e.g. (although intested)

var pagestorage = "/var/www/mysite/";
(...)
var pathname = urlparser.parse(request.url).pathname;
var requestfile = pagestorage + pathname;

Here is a full samlpe of the updated file :

 var http = require('http');
var path = require('path');
var fs = require('fs');
var urlparser = require('url');

http.createServer(function (request, response) {

    console.log('request starting...');

    var filePath = "."+request.url;
    if (filePath == './')
        filePath =  './index.html';
    else
        console.log(request.url);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    // documentation at : http://nodejs.org/api/http.html#http_request_url
    var requestedfile = urlparser.parse(request.url).pathname;
    console.log("requested URL path name : " + requestedfile);

    fs.exists( filePath, function (exists) {
        console.log("looking up : " + filePath);
        if (exists) {

            fs.readFile(filePath, function (error, content) {
                if (error) {
                    console.log("error" + error);
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': 'text/html' });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

}).listen(8125);

HTH

Upvotes: 1

Related Questions