Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

web-server.js with apache-like DirectoryIndex behavior

web-server.js with apache-like DirectoryIndex behavior

Problem

I am using the web-server.js node script to run a webserver on my local machine. The behavior of web-server.js is to dump a complete file listing if a directory is requested. instead I would like to emulate the apache DirectoryIndex where by if there is an index.html in the directory it will be served instead.

Problem courtesy of: elewinso

Solution

I could not find the answer so here is my code that does it.

first I had to change the handleRequest function

if (stat.isDirectory()) {
        var indexFile = self.getDirectoryIndex_(path);
        if (indexFile)
            return self.sendFile_(req, res, indexFile);
        return self.sendDirectory_(req, res, path);
    }

and here is my implementation to getDirectoryIndex_

StaticServlet.prototype.getDirectoryIndex_ = function(path) {
  var result = null;
  var files = fs.readdirSync(path);

  files.forEach(function(fileName, index) {
      if (fileName.match(/^index\./gi)) {
          result = path + fileName;
          return false; //break foreach loop
      }
  });

  return result;
};
Solution courtesy of: elewinso

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

web-server.js with apache-like DirectoryIndex behavior

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×