'use strict'; const styles = require('./styles'); const lastModifiedToString = require('./last-modified-to-string'); const permsToString = require('./perms-to-string'); const sizeToString = require('./size-to-string'); const sortFiles = require('./sort-files'); const fs = require('fs'); const path = require('path'); const he = require('he'); const etag = require('../etag'); const url = require('url'); const status = require('../status-handlers'); const supportedIcons = styles.icons; const css = styles.css; module.exports = (opts) => { // opts are parsed by opts.js, defaults already applied const cache = opts.cache; const root = path.resolve(opts.root); const baseDir = opts.baseDir; const humanReadable = opts.humanReadable; const hidePermissions = opts.hidePermissions; const handleError = opts.handleError; const showDotfiles = opts.showDotfiles; const si = opts.si; const weakEtags = opts.weakEtags; return function middleware(req, res, next) { // Figure out the path for the file from the given url const parsed = url.parse(req.url); const pathname = decodeURIComponent(parsed.pathname); const dir = path.normalize( path.join( root, path.relative( path.join('/', baseDir), pathname ) ) ); fs.stat(dir, (statErr, stat) => { if (statErr) { if (handleError) { status[500](res, next, { error: statErr }); } else { next(); } return; } // files are the listing of dir fs.readdir(dir, (readErr, _files) => { let files = _files; if (readErr) { if (handleError) { status[500](res, next, { error: readErr }); } else { next(); } return; } // Optionally exclude dotfiles from directory listing. if (!showDotfiles) { files = files.filter(filename => 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); function render(dirs, renderFiles, lolwuts) { // each entry in the array is a [name, stat] tuple let html = `${[ '', '', '
', ' ', ' ', ``; if (!hidePermissions) { html += ` | (${permsToString(file[1])}) | `;
}
html +=
`${lastModifiedToString(file[1])} | ` + `${sizeToString(file[1], humanReadable, si)} | ` +
`${displayName} | ` + '