-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
50 lines (38 loc) · 1.35 KB
/
index.js
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
var qs = require('querystring');
var url = require('fast-url-parser');
var join = require('path').join;
var fileExists = require('file-exists');
module.exports = function (options) {
options = options || {};
var root = options.root || './';
var indexFile = options.index || 'index.html';
var leaveOnDirectory = (options.directory === false) ? false : true;
if (options.exists) fileExists = options.exists;
return function (req, res, next) {
var pathname = url.parse(req.url).pathname;
// Don't remove tailing slash on directory index file
if (leaveOnDirectory && isDirectoryIndex() && !hasTrailingSlash()) {
return redirect(join(pathname, '/'));
}
if (leaveOnDirectory && isDirectoryIndex()) {
return next();
}
if (pathname !== '/' && hasTrailingSlash()) {
return redirect(pathname.substring(0, pathname.length - 1));
}
// no redirect needed
next();
function redirect (redirectUrl) {
var query = qs.stringify(req.query);
redirectUrl += (query) ? '?' + query : '';
res.writeHead(301, {Location: redirectUrl});
res.end();
}
function isDirectoryIndex () {
return fileExists(join(root, req.url.split('?')[0], indexFile));
}
function hasTrailingSlash () {
return pathname.substr(-1) === '/';
}
};
};