0

I am trying to make the server serve files from $HOME/public_html. This directory is the home directory of the current user. I am getting a 404 error page. I think I'm making a mistake with the syntax. Any help?

This is my code

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

var MIME_TYPES = {
    'css': 'text/css',
    'gif': 'image/gif',
    'htm': 'text/html',
    'html': 'text/html',
    'ico': 'image/x-icon',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpeg',
    'js': 'text/javascript',
    'json': 'application/json',
    'png': 'image/png',
    'txt': 'text/text'
};

var options = {
    host: 'localhost',
    port: process.env.PORT || 3000,
    index: 'index.html',
    docroot: '$HOME/Public_html'  //This where I chose to serve files from
};

var get_mime = function(filename) {
    var ext, type;
    for (ext in MIME_TYPES) {
        type = MIME_TYPES[ext];
        if (filename.indexOf(ext, filename.length - ext.length) !== -1) {
            return type;
        }
    }
    return null;
};


var respond = function(request, response, status, content, content_type) {
    if (!status) {
        status = 200;
    }

    if (!content_type) {
        content_type = 'text/plain';
    }
    console.log("" + status + "\t" +
                request.method + "\t" + request.url);
    response.writeHead(status, {
        "Content-Type": content_type
    });
    if (content) {
        response.write(content);
    }
    return response.end();
};

var serve_file = function(request, response, requestpath) {
    return fs.readFile(requestpath, function(error, content) {
        if (error != null) {
            console.error("ERROR: Encountered error while processing " +
                          request.method + " of \"" + request.url + 
                          "\".", error);
            return respond(request, response, 500);
        } else {
            return respond(request, response, 200, 
                           content, get_mime(requestpath));
        }
    });
};


var return_index = function(request, response, requestpath)  {

    var exists_callback = function(file_exists) {
        if (file_exists) {
            return serve_file(request, response, requestpath);
        } else {
            return respond(request, response, 404);
        }
    }

    if (requestpath.substr(-1) !== '/') {
        requestpath += "/";
    }
    requestpath += options.index;
    return fs.exists(requestpath, exists_callback);
}

var request_handler = function(request, response) {
    var requestpath;

    if (request.url.match(/((\.|%2E|%2e)(\.|%2E|%2e))|(~|%7E|%7e)/) != null) {
        console.warn("WARNING: " + request.method +
                     " of \"" + request.url + 
                     "\" rejected as insecure.");
        return respond(request, response, 403);
    } else {
        requestpath = path.normalize(path.join(options.docroot, request.url));
        return fs.exists(requestpath, function(file_exists) {
            if (file_exists) {
                return fs.stat(requestpath, function(err, stat) {
                    if (err != null) {
                        console.error("ERROR: Encountered error calling" +
                                      "fs.stat on \"" + requestpath + 
                                      "\" while processing " + 
                                      request.method + " of \"" + 
                                      request.url + "\".", err);
                        return respond(request, response, 500);
                    } else {
                        if ((stat != null) && stat.isDirectory()) {
                            return return_index(request, response, requestpath);
                        } else {
                            return serve_file(request, response, requestpath);
                        }
                    }
                });
            } else {
                return respond(request, response, 404);
            }
        });
    }
};

var server = http.createServer(request_handler);

server.listen(options.port, options.host, function() {
    return console.log("Server listening at http://" +
                       options.host + ":" + options.port + "/");
});

Thanks in advance!

Manuel
  • 976
  • 3
  • 9
  • 21
  • 1
    What are the errors (if any) that you are getting? What is (or isn't) happening that doesn't match your expectations? – Renato Zannon Apr 04 '14 at 20:24
  • I don't think $HOME will work. Try with absolute path in docroot. – Jakub Fedyczak Apr 04 '14 at 21:48
  • @JakubFedyczak how do I get the absolute path? Thanks – Manuel Apr 04 '14 at 22:27
  • @Manuel check if typing it by hand helps. You might also try `'~/Public_html'`. – Jakub Fedyczak Apr 04 '14 at 22:28
  • @JakubFedyczak The latter did not work. I can hand code the docroot but the problem is that this is an assignment question and tests could be carried out on another environment which may not be the same as mine – Manuel Apr 04 '14 at 22:36
  • 1
    @Manuel I found this answer, to find [home directory](http://stackoverflow.com/questions/9080085/node-js-find-home-directory-in-platform-agnostic-way). – Jakub Fedyczak Apr 04 '14 at 22:45
  • @Manuel it looks like your problem has been resolved by Jakub Fedyczak in the comments. The best way to thank the person who helped you is to invite them to post an answer that you will accept (and upvote if you have enough reputation). If this person does not wish to post an answer for any reason, you may then post your own answer **or** delete your question. (But deleting questions when you don't have much reputation can lead to a question ban, so use with care and ask a moderator if needed.) – Louis Apr 05 '14 at 10:51

0 Answers0