user4515403
user4515403

Reputation:

Why isn't "/" serving index.html in node.js?

I'm trying to write a function that returns the main page, index.html. However, when I remove the line

requestpath += options.index

I get the following error:

500: encountered error while processing GET of "/"

Without that line, wouldn't the request be localhost:3000/, which should serve index.html?

I'm guessing it has something to do with the fs.exist function at the end, but I'm not sure.

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);
}

options is equal to

{
    host: "localhost",
    port: 8080,
    index: "index.html",
    docroot: "."
}

Upvotes: 1

Views: 198

Answers (2)

royhowie
royhowie

Reputation: 11171

fs.exists checks whether a file exists in the file system. Since requestpath += options.index is changing / to /index.html, without it fs.exists will not find a file. (/ is a directory, not a file, hence the error.)

This may seem confusing since localhost:3000/ should serve index.html. On the web, / is shorthand for index.html (unless you have the default file set to something else). When you ask for /, the file system looks for index.html and, if it exists, serves it.

I would change your code to:

var getIndex = function (req, res, path)  {    
    if (path.slice(-1) !== "/")
        path += "/";
    path += options.index;
    return fs.exists(path, function (file) {
        return file ? serve_file(req, res, path) : respond(req, res, 404);
    });
}

Try and make callbacks anonymous, unless you know you're going to use them elsewhere. Above, exists_callback was only going to be used once, so save some code and pass it as an anonymous function. Also, in node.js, you should use camelCase and not underscores, e.g., getIndex over return_index.

Upvotes: 1

lujcon
lujcon

Reputation: 586

It looks that requestpath maps uri to file system - but it is not pointing to a specific file(ex: http://localhost/ maps to /myrootpath/). What you want to do is to serve default file from that folder (ex: index.html) which I think is stored in options.index. That's why you have to append options.index to the path.

Upvotes: 0

Related Questions