Compare commits

...

33 Commits

Author SHA1 Message Date
Douglas Christopher Wilson
f17363a45d 1.7.1 2015-07-05 23:32:34 -04:00
Douglas Christopher Wilson
db2163892e deps: mime-types@~2.1.2 2015-07-05 23:30:07 -04:00
Douglas Christopher Wilson
5c74d1e44a deps: accepts@~1.2.10 2015-07-05 23:29:30 -04:00
Douglas Christopher Wilson
bd6f5553a5 build: io.js@2.3 2015-07-05 23:28:22 -04:00
Douglas Christopher Wilson
63b45e6208 1.7.0 2015-06-15 16:50:22 -04:00
Douglas Christopher Wilson
d680e6302d Accept function value for template option
closes #20
closes #30
2015-06-14 23:07:52 -04:00
Douglas Christopher Wilson
420d159be7 Stat parent directory when necessary 2015-06-14 22:29:58 -04:00
Douglas Christopher Wilson
6d3160a32c Use Date.prototype.toLocaleDateString to format date 2015-06-14 22:01:22 -04:00
Douglas Christopher Wilson
4056d3375c deps: mime-types@~2.1.1 2015-06-14 21:17:01 -04:00
Douglas Christopher Wilson
7566e487b0 deps: accepts@~1.2.9 2015-06-14 21:14:45 -04:00
Douglas Christopher Wilson
3ae1ea56d3 perf: remove argument reassignment 2015-06-14 21:13:27 -04:00
Douglas Christopher Wilson
d60c7a0055 Send non-chunked response for OPTIONS 2015-06-14 21:01:42 -04:00
Douglas Christopher Wilson
6781d9536b perf: enable strict mode 2015-06-14 21:00:45 -04:00
Douglas Christopher Wilson
ea919ec568 deps: escape-html@1.0.2 2015-06-14 20:59:38 -04:00
Douglas Christopher Wilson
07611f42ad build: supertest@1.0.1 2015-06-14 20:56:13 -04:00
Douglas Christopher Wilson
e4355f0e97 build: mocha@2.2.5 2015-06-14 20:55:24 -04:00
Douglas Christopher Wilson
5275b835a7 build: io.js@2.1 2015-06-14 20:54:28 -04:00
Douglas Christopher Wilson
636a8ae7bc 1.6.4 2015-05-12 21:28:44 -04:00
Douglas Christopher Wilson
320226f35a deps: mime-types@~2.0.11 2015-05-12 21:00:31 -04:00
Douglas Christopher Wilson
2003c3f743 deps: mocha@~2.2.4 2015-05-12 20:59:49 -04:00
Douglas Christopher Wilson
e385089155 deps: debug@~2.2.0 2015-05-12 20:59:15 -04:00
Douglas Christopher Wilson
5462db3946 deps: accepts@~1.2.7 2015-05-12 20:58:24 -04:00
Douglas Christopher Wilson
cb60444cb1 deps: istanbul@0.3.9 2015-05-12 20:57:39 -04:00
Douglas Christopher Wilson
6691f1b75e build: support io.js 2.x 2015-05-12 14:46:31 -04:00
Douglas Christopher Wilson
5cb8bcc448 build: io.js@1.8 2015-05-12 13:14:15 -04:00
Douglas Christopher Wilson
e11f253226 1.6.3 2015-03-14 01:22:30 -04:00
Douglas Christopher Wilson
7381a1d145 Properly escape file names in HTML
fixes #28
2015-03-13 22:34:00 -04:00
Douglas Christopher Wilson
6a4a87edcd build: support io.js 1.x 2015-03-13 22:25:52 -04:00
Douglas Christopher Wilson
99e8ec512a deps: mime-types@~2.0.10 2015-03-13 22:24:20 -04:00
Douglas Christopher Wilson
197d9f6a0f deps: accepts@~1.2.5 2015-03-13 22:23:39 -04:00
Douglas Christopher Wilson
41fe20602a deps: debug@~2.1.3 2015-03-13 21:33:11 -04:00
Douglas Christopher Wilson
b5c886f36d deps: mocha@~2.2.1 2015-03-12 19:03:04 -04:00
Douglas Christopher Wilson
6da896f6d8 deps: istanbul@0.3.7 2015-03-11 22:43:09 -04:00
11 changed files with 460 additions and 169 deletions

View File

@@ -3,6 +3,10 @@ node_js:
- "0.8"
- "0.10"
- "0.12"
- "1.0"
- "1.8"
- "2.0"
- "2.3"
sudo: false
script: "npm run-script test-ci"
after_script: "npm install coveralls@2.10.0 && cat ./coverage/lcov.info | coveralls"

View File

@@ -1,3 +1,55 @@
1.7.1 / 2015-07-05
==================
* deps: accepts@~1.2.10
- deps: mime-types@~2.1.2
* deps: mime-types@~2.1.2
- Add new mime types
1.7.0 / 2015-06-15
==================
* Accept `function` value for `template` option
* Send non-chunked response for `OPTIONS`
* Stat parent directory when necessary
* Use `Date.prototype.toLocaleDateString` to format date
* deps: accepts@~1.2.9
- deps: mime-types@~2.1.1
- deps: negotiator@0.5.3
- perf: avoid argument reassignment & argument slice
- perf: avoid negotiator recursive construction
- perf: enable strict mode
- perf: remove unnecessary bitwise operator
* deps: escape-html@1.0.2
* deps: mime-types@~2.1.1
- Add new mime types
* perf: enable strict mode
* perf: remove argument reassignment
1.6.4 / 2015-05-12
==================
* deps: accepts@~1.2.7
- deps: mime-types@~2.0.11
- deps: negotiator@0.5.3
* deps: debug@~2.2.0
- deps: ms@0.7.1
* deps: mime-types@~2.0.11
- Add new mime types
1.6.3 / 2015-03-13
==================
* Properly escape file names in HTML
* deps: accepts@~1.2.5
- deps: mime-types@~2.0.10
* deps: debug@~2.1.3
- Fix high intensity foreground color for bold
- deps: ms@0.7.0
* deps: escape-html@1.0.1
* deps: mime-types@~2.0.10
- Add new mime types
1.6.2 / 2015-02-16
==================

View File

@@ -3,7 +3,7 @@
Copyright (c) 2010 Sencha Inc.
Copyright (c) 2011 LearnBoost
Copyright (c) 2011 TJ Holowaychuk
Copyright (c) 2014 Douglas Christopher Wilson
Copyright (c) 2014-2015 Douglas Christopher Wilson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the

View File

@@ -56,15 +56,31 @@ Optional path to a CSS stylesheet. Defaults to a built-in stylesheet.
##### template
Optional path to an HTML template. Defaults to a built-in template.
Optional path to an HTML template or a function that will render a HTML
string. Defaults to a built-in template.
The following tokens are replaced in templates:
When given a string, the string is used as a file path to load and then the
following tokens are replaced in templates:
* `{directory}` with the name of the directory.
* `{files}` with the HTML of an unordered list of file links.
* `{linked-path}` with the HTML of a link to the directory.
* `{style}` with the specified stylesheet and embedded images.
When given as a function, the function is called as `template(locals, callback)`
and it needs to invoke `callback(error, htmlString)`. The following are the
provided locals:
* `directory` is the directory being displayed (where `/` is the root).
* `displayIcons` is a Boolean for if icons should be rendered or not.
* `fileList` is a sorted array of files in the directory. The array contains
objects with the following properties:
- `name` is the relative name for the file.
- `stat` is a `fs.Stats` object for the file.
* `path` is the full filesystem path to `directory`.
* `style` is the default stylesheet or the contents of the `stylesheet` option.
* `viewName` is the view name provided by the `view` option.
##### view
Display mode. `tiles` and `details` are available. Defaults to `tiles`.

View File

@@ -3,6 +3,10 @@ environment:
- nodejs_version: "0.8"
- nodejs_version: "0.10"
- nodejs_version: "0.12"
- nodejs_version: "1.0"
- nodejs_version: "1.8"
- nodejs_version: "2.0"
- nodejs_version: "2.3"
install:
- ps: Install-Product node $env:nodejs_version
- npm install

282
index.js
View File

@@ -2,20 +2,21 @@
* serve-index
* Copyright(c) 2011 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* Copyright(c) 2014 Douglas Christopher Wilson
* Copyright(c) 2014-2015 Douglas Christopher Wilson
* MIT Licensed
*/
// TODO: arrow key navigation
// TODO: make icons extensible
'use strict';
/**
* Module dependencies.
* @private
*/
var accepts = require('accepts');
var createError = require('http-errors');
var debug = require('debug')('serve-index');
var escapeHtml = require('escape-html');
var fs = require('fs')
, path = require('path')
, normalize = path.normalize
@@ -27,6 +28,13 @@ var mime = require('mime-types');
var parseUrl = require('parseurl');
var resolve = require('path').resolve;
/**
* Module exports.
* @public
*/
module.exports = serveIndex;
/*!
* Icon cache.
*/
@@ -66,35 +74,35 @@ var mediaType = {
*
* See Readme.md for documentation of options.
*
* @param {String} path
* @param {String} root
* @param {Object} options
* @return {Function} middleware
* @api public
* @public
*/
exports = module.exports = function serveIndex(root, options){
options = options || {};
function serveIndex(root, options) {
var opts = options || {};
// root required
if (!root) throw new TypeError('serveIndex() root path required');
if (!root) {
throw new TypeError('serveIndex() root path required');
}
// resolve root to absolute and normalize
root = resolve(root);
root = normalize(root + sep);
var rootPath = normalize(resolve(root) + sep);
var hidden = options.hidden
, icons = options.icons
, view = options.view || 'tiles'
, filter = options.filter
, template = options.template || defaultTemplate
, stylesheet = options.stylesheet || defaultStylesheet;
var filter = opts.filter;
var hidden = opts.hidden;
var icons = opts.icons;
var stylesheet = opts.stylesheet || defaultStylesheet;
var template = opts.template || defaultTemplate;
var view = opts.view || 'tiles';
return function serveIndex(req, res, next) {
return function (req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.statusCode = 'OPTIONS' === req.method
? 200
: 405;
res.statusCode = 'OPTIONS' === req.method ? 200 : 405;
res.setHeader('Allow', 'GET, HEAD, OPTIONS');
res.setHeader('Content-Length', '0');
res.end();
return;
}
@@ -106,19 +114,19 @@ exports = module.exports = function serveIndex(root, options){
var originalDir = decodeURIComponent(originalUrl.pathname);
// join / normalize from root dir
var path = normalize(join(root, dir));
var path = normalize(join(rootPath, dir));
// null byte(s), bad request
if (~path.indexOf('\0')) return next(createError(400));
// malicious path
if ((path + sep).substr(0, root.length) !== root) {
if ((path + sep).substr(0, rootPath.length) !== rootPath) {
debug('malicious path "%s"', path);
return next(createError(403));
}
// determine ".." display
var showUp = normalize(resolve(path) + sep) !== root;
var showUp = normalize(resolve(path) + sep) !== rootPath;
// check if we have a directory
debug('stat "%s"', path);
@@ -152,7 +160,7 @@ exports = module.exports = function serveIndex(root, options){
// not acceptable
if (!type) return next(createError(406));
exports[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template, stylesheet);
serveIndex[mediaType[type]](req, res, files, next, originalDir, showUp, icons, path, view, template, stylesheet);
});
});
};
@@ -162,23 +170,46 @@ exports = module.exports = function serveIndex(root, options){
* Respond with text/html.
*/
exports.html = function(req, res, files, next, dir, showUp, icons, path, view, template, stylesheet){
fs.readFile(template, 'utf8', function(err, str){
if (err) return next(err);
fs.readFile(stylesheet, 'utf8', function(err, style){
if (err) return next(err);
stat(path, files, function(err, stats){
if (err) return next(err);
files = files.map(function(file, i){ return { name: file, stat: stats[i] }; });
files.sort(fileSort);
if (showUp) files.unshift({ name: '..' });
str = str
.replace(/\{style\}/g, style.concat(iconStyle(files, icons)))
.replace(/\{files\}/g, html(files, dir, icons, view))
.replace(/\{directory\}/g, dir)
.replace(/\{linked-path\}/g, htmlPath(dir));
serveIndex.html = function _html(req, res, files, next, dir, showUp, icons, path, view, template, stylesheet) {
var render = typeof template !== 'function'
? createHtmlRender(template)
: template
var buf = new Buffer(str, 'utf8');
if (showUp) {
files.unshift('..');
}
// stat all files
stat(path, files, function (err, stats) {
if (err) return next(err);
// combine the stats into the file list
var fileList = files.map(function (file, i) {
return { name: file, stat: stats[i] };
});
// sort file list
fileList.sort(fileSort);
// read stylesheet
fs.readFile(stylesheet, 'utf8', function (err, style) {
if (err) return next(err);
// create locals for rendering
var locals = {
directory: dir,
displayIcons: Boolean(icons),
fileList: fileList,
path: path,
style: style,
viewName: view
};
// render html
render(locals, function (err, body) {
if (err) return next(err);
var buf = new Buffer(body, 'utf8');
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.setHeader('Content-Length', buf.length);
res.end(buf);
@@ -191,7 +222,7 @@ exports.html = function(req, res, files, next, dir, showUp, icons, path, view, t
* Respond with application/json.
*/
exports.json = function(req, res, files){
serveIndex.json = function _json(req, res, files) {
var body = JSON.stringify(files);
var buf = new Buffer(body, 'utf8');
@@ -204,7 +235,7 @@ exports.json = function(req, res, files){
* Respond with text/plain.
*/
exports.plain = function(req, res, files){
serveIndex.plain = function _plain(req, res, files) {
var body = files.join('\n') + '\n';
var buf = new Buffer(body, 'utf8');
@@ -213,11 +244,99 @@ exports.plain = function(req, res, files){
res.end(buf);
};
/**
* Map html `files`, returning an html unordered list.
* @private
*/
function createHtmlFileList(files, dir, useIcons, view) {
var html = '<ul id="files" class="view-' + escapeHtml(view) + '">'
+ (view == 'details' ? (
'<li class="header">'
+ '<span class="name">Name</span>'
+ '<span class="size">Size</span>'
+ '<span class="date">Modified</span>'
+ '</li>') : '');
html += files.map(function (file) {
var classes = [];
var isDir = file.stat && file.stat.isDirectory();
var path = dir.split('/').map(function (c) { return encodeURIComponent(c); });
if (useIcons) {
classes.push('icon');
if (isDir) {
classes.push('icon-directory');
} else {
var ext = extname(file.name);
var icon = iconLookup(file.name);
classes.push('icon');
classes.push('icon-' + ext.substring(1));
if (classes.indexOf(icon.className) === -1) {
classes.push(icon.className);
}
}
}
path.push(encodeURIComponent(file.name));
var date = file.stat && file.name !== '..'
? file.stat.mtime.toLocaleDateString() + ' ' + file.stat.mtime.toLocaleTimeString()
: '';
var size = file.stat && !isDir
? file.stat.size
: '';
return '<li><a href="'
+ escapeHtml(normalizeSlashes(normalize(path.join('/'))))
+ '" class="' + escapeHtml(classes.join(' ')) + '"'
+ ' title="' + escapeHtml(file.name) + '">'
+ '<span class="name">' + escapeHtml(file.name) + '</span>'
+ '<span class="size">' + escapeHtml(size) + '</span>'
+ '<span class="date">' + escapeHtml(date) + '</span>'
+ '</a></li>';
}).join('\n');
html += '</ul>';
return html;
}
/**
* Create function to render html.
*/
function createHtmlRender(template) {
return function render(locals, callback) {
// read template
fs.readFile(template, 'utf8', function (err, str) {
if (err) return callback(err);
var body = str
.replace(/\{style\}/g, locals.style.concat(iconStyle(locals.fileList, locals.displayIcons)))
.replace(/\{files\}/g, createHtmlFileList(locals.fileList, locals.directory, locals.displayIcons, locals.viewName))
.replace(/\{directory\}/g, escapeHtml(locals.directory))
.replace(/\{linked-path\}/g, htmlPath(locals.directory));
callback(null, body);
});
};
}
/**
* Sort function for with directories first.
*/
function fileSort(a, b) {
// sort ".." to the top
if (a.name === '..' || b.name === '..') {
return a.name === b.name ? 0
: a.name === '..' ? -1 : 1;
}
return Number(b.stat && b.stat.isDirectory()) - Number(a.stat && a.stat.isDirectory()) ||
String(a.name).toLocaleLowerCase().localeCompare(String(b.name).toLocaleLowerCase());
}
@@ -227,11 +346,19 @@ function fileSort(a, b) {
*/
function htmlPath(dir) {
var curr = [];
return dir.split('/').map(function(part){
curr.push(encodeURIComponent(part));
return part ? '<a href="' + curr.join('/') + '">' + part + '</a>' : '';
}).join(' / ');
var parts = dir.split('/');
var crumb = new Array(parts.length);
for (var i = 0; i < parts.length; i++) {
var part = parts[i];
if (part) {
parts[i] = encodeURIComponent(part);
crumb[i] = '<a href="' + escapeHtml(parts.slice(0, i + 1).join('/')) + '">' + escapeHtml(part) + '</a>';
}
}
return crumb.join(' / ');
}
/**
@@ -296,7 +423,7 @@ function iconLookup(filename) {
* Load icon images, return css string.
*/
function iconStyle (files, useIcons) {
function iconStyle(files, useIcons) {
if (!useIcons) return '';
var className;
var i;
@@ -310,7 +437,7 @@ function iconStyle (files, useIcons) {
for (i = 0; i < files.length; i++) {
var file = files[i];
var isDir = '..' == file.name || (file.stat && file.stat.isDirectory());
var isDir = file.stat && file.stat.isDirectory();
var icon = isDir
? { className: 'icon-directory', fileName: icons.folder }
: iconLookup(file.name);
@@ -337,63 +464,6 @@ function iconStyle (files, useIcons) {
return style;
}
/**
* Map html `files`, returning an html unordered list.
*/
function html(files, dir, useIcons, view) {
return '<ul id="files" class="view-' + view + '">'
+ (view == 'details' ? (
'<li class="header">'
+ '<span class="name">Name</span>'
+ '<span class="size">Size</span>'
+ '<span class="date">Modified</span>'
+ '</li>') : '')
+ files.map(function(file){
var isDir = '..' == file.name || (file.stat && file.stat.isDirectory())
, classes = []
, path = dir.split('/').map(function (c) { return encodeURIComponent(c); });
if (useIcons) {
classes.push('icon');
if (isDir) {
classes.push('icon-directory');
} else {
var ext = extname(file.name);
var icon = iconLookup(file.name);
classes.push('icon');
classes.push('icon-' + ext.substring(1));
if (classes.indexOf(icon.className) === -1) {
classes.push(icon.className);
}
}
}
path.push(encodeURIComponent(file.name));
var date = file.stat && file.name !== '..'
? file.stat.mtime.toDateString() + ' ' + file.stat.mtime.toLocaleTimeString()
: '';
var size = file.stat && !isDir
? file.stat.size
: '';
return '<li><a href="'
+ normalizeSlashes(normalize(path.join('/')))
+ '" class="'
+ classes.join(' ') + '"'
+ ' title="' + file.name + '">'
+ '<span class="name">'+file.name+'</span>'
+ '<span class="size">'+size+'</span>'
+ '<span class="date">'+date+'</span>'
+ '</a></li>';
}).join('\n') + '</ul>';
}
/**
* Load and cache the given `icon`.
*

View File

@@ -1,23 +1,24 @@
{
"name": "serve-index",
"description": "Serve directory listings",
"version": "1.6.2",
"version": "1.7.1",
"author": "Douglas Christopher Wilson <doug@somethingdoug.com>",
"license": "MIT",
"repository": "expressjs/serve-index",
"dependencies": {
"accepts": "~1.2.4",
"accepts": "~1.2.10",
"batch": "0.5.2",
"debug": "~2.1.1",
"debug": "~2.2.0",
"escape-html": "1.0.2",
"http-errors": "~1.3.1",
"mime-types": "~2.0.9",
"mime-types": "~2.1.2",
"parseurl": "~1.3.0"
},
"devDependencies": {
"after": "0.8.1",
"istanbul": "0.3.5",
"mocha": "~2.1.0",
"supertest": "~0.15.0"
"istanbul": "0.3.9",
"mocha": "2.2.5",
"supertest": "1.0.1"
},
"files": [
"public/",

1
test/fixtures/users/#dir/tobi.txt vendored Normal file
View File

@@ -0,0 +1 @@
ferret

View File

@@ -109,7 +109,7 @@ describe('serveIndex(root)', function () {
.get('/')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(/g# %3 o %2525 %37 dir/)
.expect(/g# %3 o & %2525 %37 dir/)
.expect(/users/)
.expect(/file #1\.txt/)
.expect(/nums/)
@@ -128,7 +128,7 @@ describe('serveIndex(root)', function () {
.set('Accept', 'text/html')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
.expect(/<a href="\/g%23%20%253%20o%20%26%20%252525%20%2537%20dir"/)
.expect(/<a href="\/users"/)
.expect(/<a href="\/file%20%231.txt"/)
.expect(/<a href="\/todo.txt"/)
@@ -136,6 +136,20 @@ describe('serveIndex(root)', function () {
.end(done);
});
it('should property escape file names', function (done) {
var server = createServer()
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(/<a href="\/foo%20%26%20bar"/)
.expect(/foo &amp; bar/)
.expect(bodyDoesNotContain('foo & bar'))
.end(done);
});
it('should sort folders first', function (done) {
var server = createServer()
@@ -151,10 +165,10 @@ describe('serveIndex(root)', function () {
assert.deepEqual(urls, [
'/%23directory',
'/collect',
'/g%23%20%253%20o%20%252525%20%2537%20dir',
'/g%23%20%253%20o%20%26%20%252525%20%2537%20dir',
'/users',
'/file%20%231.txt',
'/foo%20bar',
'/foo%20%26%20bar',
'/nums',
'/todo.txt',
'/%E3%81%95%E3%81%8F%E3%82%89.txt'
@@ -174,7 +188,7 @@ describe('serveIndex(root)', function () {
.expect(200)
.expect('Content-Type', 'text/plain; charset=utf-8')
.expect(/users/)
.expect(/g# %3 o %2525 %37 dir/)
.expect(/g# %3 o & %2525 %37 dir/)
.expect(/file #1.txt/)
.expect(/todo.txt/)
.expect(/さくら\.txt/)
@@ -256,7 +270,7 @@ describe('serveIndex(root)', function () {
});
it('should filter directory paths', function (done) {
var cb = after(3, done)
var cb = after(4, done)
var server = createServer(fixtures, {'filter': filter})
function filter(name, index, list, dir) {
@@ -290,6 +304,146 @@ describe('serveIndex(root)', function () {
});
});
describe('with "template" option', function () {
describe('when setting a custom template file', function () {
var server;
before(function () {
server = createServer(fixtures, {'template': __dirname + '/shared/template.html'});
});
it('should respond with file list', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(/<a href="\/g%23%20%253%20o%20%26%20%252525%20%2537%20dir"/)
.expect(/<a href="\/users"/)
.expect(/<a href="\/file%20%231.txt"/)
.expect(/<a href="\/todo.txt"/)
.expect(200, done)
});
it('should respond with testing template sentence', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200, /This is the test template/, done)
});
it('should have default styles', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200, /ul#files/, done)
});
it('should list directory twice', function (done) {
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(function (res) {
var occurances = res.text.match(/directory \/users\//g)
if (occurances && occurances.length === 2) return
throw new Error('directory not listed twice')
})
.expect(200, done)
});
});
describe('when setting a custom template function', function () {
it('should invoke function to render', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, 'This is a template.');
}});
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200, 'This is a template.', done);
});
it('should handle render errors', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(new Error('boom!'));
}});
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(500, 'boom!', done);
});
it('should provide "directory" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.directory));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(200, '"/users/"', done);
});
it('should provide "displayIcons" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.displayIcons));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(200, 'false', done);
});
it('should provide "fileList" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.fileList.map(function (file) {
file.stat = file.stat instanceof fs.Stats;
return file;
})));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect('[{"name":"..","stat":true},{"name":"#dir","stat":true},{"name":"index.html","stat":true},{"name":"tobi.txt","stat":true}]')
.expect(200, done);
});
it('should provide "path" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.path));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(200, JSON.stringify(path.join(fixtures, 'users/')), done);
});
it('should provide "style" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.style));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(200, /#files \.icon \.name/, done);
});
it('should provide "viewName" local', function (done) {
var server = createServer(fixtures, {'template': function (locals, callback) {
callback(null, JSON.stringify(locals.viewName));
}});
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(200, '"tiles"', done);
});
});
});
describe('when using custom handler', function () {
describe('exports.html', function () {
alterProperty(serveIndex, 'html', serveIndex.html)
@@ -437,6 +591,25 @@ describe('serveIndex(root)', function () {
.end(done);
});
it('should include link to parent directory', function (done) {
var server = createServer()
request(server)
.get('/users')
.end(function (err, res) {
if (err) return done(err);
var body = res.text.split('</h1>')[1];
var urls = body.split(/<a href="([^"]*)"/).filter(function(s, i){ return i%2; });
assert.deepEqual(urls, [
'/',
'/users/%23dir',
'/users/index.html',
'/users/tobi.txt'
]);
done();
});
});
it('should work for directory with #', function (done) {
var server = createServer()
@@ -454,12 +627,26 @@ describe('serveIndex(root)', function () {
var server = createServer()
request(server)
.get('/g%23%20%253%20o%20%252525%20%2537%20dir/')
.get('/g%23%20%253%20o%20%26%20%252525%20%2537%20dir/')
.set('Accept', 'text/html')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
.expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir\/empty.txt"/)
.expect(/<a href="\/g%23%20%253%20o%20%26%20%252525%20%2537%20dir"/)
.expect(/<a href="\/g%23%20%253%20o%20%26%20%252525%20%2537%20dir\/empty.txt"/)
.end(done);
});
it('should property escape directory names', function (done) {
var server = createServer()
request(server)
.get('/g%23%20%253%20o%20%26%20%252525%20%2537%20dir/')
.set('Accept', 'text/html')
.expect(200)
.expect('Content-Type', 'text/html; charset=utf-8')
.expect(/<a href="\/g%23%20%253%20o%20%26%20%252525%20%2537%20dir"/)
.expect(/g# %3 o &amp; %2525 %37 dir/)
.expect(bodyDoesNotContain('g# %3 o & %2525 %37 dir'))
.end(done);
});
@@ -473,50 +660,6 @@ describe('serveIndex(root)', function () {
});
});
describe('when setting a custom template', function () {
var server;
before(function () {
server = createServer(fixtures, {'template': __dirname + '/shared/template.html'});
});
it('should respond with file list', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
.expect(/<a href="\/users"/)
.expect(/<a href="\/file%20%231.txt"/)
.expect(/<a href="\/todo.txt"/)
.expect(200, done)
});
it('should respond with testing template sentence', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200, /This is the test template/, done)
});
it('should have default styles', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect(200, /ul#files/, done)
});
it('should list directory twice', function (done) {
request(server)
.get('/users/')
.set('Accept', 'text/html')
.expect(function (res) {
var occurances = res.text.match(/directory \/users\//g)
if (occurances && occurances.length === 2) return
throw new Error('directory not listed twice')
})
.expect(200, done)
});
});
describe('when setting a custom stylesheet', function () {
var server;
before(function () {