Aug 13

Auto index in JSON

I’m in the process of setting up my personal dedicated server. One of the standard features of web servers is creating automatic responses for directory content listing. There is mod_autoindex for Apache, and autoindex for Nginx. Both are able to produce nice and simply looking web pages that allow to navigate a directory structure on the server. What they cannot produce is a response that is actually useful for consumption by client software – a JSON response. Because of that they are not suitable for Javascript parsing.

During my research I found out that there is a Node.js middleware (a part of Connect module) doing exactly what I was looking for. It creates directory listings and serves them in various formats. A Node.js instance running directory listing script can be put behind a reverse proxy to better integrate with the remaining services and for performance reasons.

The problem with a default directory middleware JSON response is lack of any information about the files apart from their names. As a result it’s hard to deduct for the client if file entry is a file or actually a directory. In many applications some additional metadata might be useful as well. To address this problem I replaced the implementation of JSON response construction function with the following one:

express.directory.json = function(req, res, files, next, dir, showUp, icons){
  var richFiles = files.map(function(file) {
    var fileStats = fs.lstatSync(root + dir + file);
    return {
        'name': file,
        'isDirectory': fileStats.isDirectory()
  files = JSON.stringify({
    'files': richFiles,
    'path': dir,
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Content-Length', files.length);

As opposed to the original, my json function can use all the parameters passed by directory middleware. Each file is checked for being a directory. Also, a current path relative to the root is returned. To improve the performance on non frequently changing directory structures (e.g. image galleries) caching can be enabled on reverse proxy.

I shared the code of this short Node script on github. Feel free to fork it and reuse it for your needs.

Leave a Reply

Your email address will not be published.