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.