1

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: "."
}
3
  • 2
    In what context, is this Node.js, and what does requestpath do? It looks like the difference would be absolute and relative paths Commented Jan 31, 2015 at 19:47
  • And what is options.index? Can you console.log(options.index); and tell us what it returns? Commented Jan 31, 2015 at 19:50
  • yes it is node.js. I will update the post with option.index Commented Jan 31, 2015 at 19:51

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.