all files / lib/ecstatic/ showdir.js

89.29% Statements 75/84
70.37% Branches 38/54
88.89% Functions 16/18
91.25% Lines 73/80
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 22535×               35×   12×                 12×     12×                     12× 12×         12× 12×         12×           12× 12× 12× 12×   12×                   12×             35×       12×         12×     11× 157× 157×     157× 57×     100×     157× 11×           35×       12×                       12×   12× 12×   160× 160×     160× 60×     160×     160×             49× 192× 12×   12× 12×               12× 12× 12×               35×   160×       160×     160× 480×                                 35× 160× 60×     100× 100× 100×   100× 52×     48× 48× 48× 48× 48×     48× 48×   48×    
var ecstatic = require('../ecstatic'),
    fs = require('fs'),
    path = require('path'),
    he = require('he'),
    etag = require('./etag'),
    url = require('url'),
    status = require('./status-handlers');
 
module.exports = function (opts, stat) {
  // opts are parsed by opts.js, defaults already applied
  var cache = opts.cache,
      root = path.resolve(opts.root),
      baseDir = opts.baseDir,
      humanReadable = opts.humanReadable,
      handleError = opts.handleError,
      showDotfiles = opts.showDotfiles,
      si = opts.si,
      weakEtags = opts.weakEtags;
 
  return function middleware (req, res, next) {
 
    // Figure out the path for the file from the given url
    var parsed = url.parse(req.url),
        pathname = decodeURIComponent(parsed.pathname),
        dir = path.normalize(
          path.join(root,
            path.relative(
              path.join('/', baseDir),
              pathname
            )
          )
        );
 
    fs.stat(dir, function (err, stat) {
      Iif (err) {
        return handleError ? status[500](res, next, { error: err }) : next();
      }
 
      // files are the listing of dir
      fs.readdir(dir, function (err, files) {
        Iif (err) {
          return handleError ? status[500](res, next, { error: err }) : next();
        }
 
        // Optionally exclude dotfiles from directory listing.
        Iif (!showDotfiles) {
          files = files.filter(function(filename){
            return filename.slice(0,1) !== '.';
          });
        }
 
        res.setHeader('content-type', 'text/html');
        res.setHeader('etag', etag(stat, weakEtags));
        res.setHeader('last-modified', (new Date(stat.mtime)).toUTCString());
        res.setHeader('cache-control', cache);
 
        sortByIsDirectory(files, function (lolwuts, dirs, files) {
          // It's possible to get stat errors for all sorts of reasons here.
          // Unfortunately, our two choices are to either bail completely,
          // or just truck along as though everything's cool. In this case,
          // I decided to just tack them on as "??!?" items along with dirs
          // and files.
          //
          // Whatever.
 
          // if it makes sense to, add a .. link
          if (path.resolve(dir, '..').slice(0, root.length) == root) {
            return fs.stat(path.join(dir, '..'), function (err, s) {
              Iif (err) {
                return handleError ? status[500](res, next, { error: err }) : next();
              }
              dirs.unshift([ '..', s ]);
              render(dirs, files, lolwuts);
            });
          }
          render(dirs, files, lolwuts);
        });
 
        function sortByIsDirectory(paths, cb) {
          // take the listing file names in `dir`
          // returns directory and file array, each entry is
          // of the array a [name, stat] tuple
          var pending = paths.length,
              errs = [],
              dirs = [],
              files = [];
 
          if (!pending) {
            return cb(errs, dirs, files);
          }
 
          paths.forEach(function (file) {
            fs.stat(path.join(dir, file), function (err, s) {
              Iif (err) {
                errs.push([file, err]);
              }
              else if (s.isDirectory()) {
                dirs.push([file, s]);
              }
              else {
                files.push([file, s]);
              }
 
              if (--pending === 0) {
                cb(errs, dirs, files);
              }
            });
          });
        }
 
        function render(dirs, files, lolwuts) {
          // each entry in the array is a [name, stat] tuple
 
          // TODO: use stylessheets?
          var html = [
            '<!doctype html>',
            '<html>',
            '  <head>',
            '    <meta charset="utf-8">',
            '    <meta name="viewport" content="width=device-width">',
            '    <title>Index of ' + he.encode(pathname) +'</title>',
            '  </head>',
            '  <body>',
            '<h1>Index of ' + he.encode(pathname) + '</h1>'
          ].join('\n') + '\n';
 
          html += '<table>';
 
          var failed = false;
          var writeRow = function (file, i) {
            // render a row given a [name, stat] tuple
            var isDir = file[1].isDirectory && file[1].isDirectory();
            var href = parsed.pathname.replace(/\/$/, '') + '/' + encodeURIComponent(file[0]);
 
            // append trailing slash and query for dir entry
            if (isDir) {
              href += '/' + he.encode((parsed.search)? parsed.search:'');
            }
 
            var displayName = he.encode(file[0]) + ((isDir)? '/':'');
 
            // TODO: use stylessheets?
            html += '<tr>' +
              '<td><code>(' + permsToString(file[1]) + ')</code></td>' +
              '<td style="text-align: right; padding-left: 1em"><code>' + sizeToString(file[1], humanReadable, si) + '</code></td>' +
              '<td style="padding-left: 1em"><a href="' + href + '">' + displayName + '</a></td>' +
              '</tr>\n';
          };
 
          dirs.sort(function (a, b) { return a[0].toString().localeCompare(b[0].toString()); }).forEach(writeRow);
          files.sort(function (a, b) { return a.toString().localeCompare(b.toString()); }).forEach(writeRow);
          lolwuts.sort(function (a, b) { return a[0].toString().localeCompare(b[0].toString()); }).forEach(writeRow);
 
          html += '</table>\n';
          html += '<br><address>Node.js ' +
            process.version +
            '/ <a href="https://github.com/jfhbrook/node-ecstatic">ecstatic</a> ' +
            'server running @ ' +
            he.encode(req.headers.host || '') + '</address>\n' +
            '</body></html>'
          ;
 
          Eif (!failed) {
            res.writeHead(200, { "Content-Type": "text/html" });
            res.end(html);
          }
        }
      });
    });
  };
};
 
function permsToString(stat) {
 
  Iif (!stat.isDirectory || !stat.mode) {
    return '???!!!???';
  }
 
  var dir = stat.isDirectory() ? 'd' : '-',
      mode = stat.mode.toString(8);
 
  return dir + mode.slice(-3).split('').map(function (n) {
    return [
      '---',
      '--x',
      '-w-',
      '-wx',
      'r--',
      'r-x',
      'rw-',
      'rwx'
    ][parseInt(n, 10)];
  }).join('');
}
 
// given a file's stat, return the size of it in string
// humanReadable: (boolean) whether to result is human readable
// si: (boolean) whether to use si (1k = 1000), otherwise 1k = 1024
// adopted from http://stackoverflow.com/a/14919494/665507
function sizeToString(stat, humanReadable, si) {
    if (stat.isDirectory && stat.isDirectory()) {
      return '';
    }
 
    var sizeString = '';
    var bytes = stat.size;
    var threshold = si ? 1000 : 1024;
 
    if (!humanReadable || bytes < threshold) {
      return bytes + 'B';
    }
 
    var units = [ 'k','M','G','T','P','E','Z','Y' ];
    var u = -1;
    do {
        bytes /= threshold;
        ++u;
    } while (bytes >= threshold);
 
    var b = bytes.toFixed(1);
    Iif (isNaN(b)) b = '??';
 
    return b + units[u];
}