-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
68 lines (62 loc) · 1.7 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
const util = require('util');
const fs = require('fs');
const stat = util.promisify(fs.stat)
const readdir = util.promisify(fs.readdir)
const URL = require('url')
const path = require('path')
const normalize = path.normalize
const join = path.join;
function removeHidden(files) {
return files.filter(function (file) {
return file[0] !== '.'
});
}
/**
* autoindex
* @param {string} rootPath - the path you want to autoindex
* @param {Object} [opts] - {filter: a -> Boolean , removeHidden: Boolean}
* @returns {generater}
*/
module.exports = function (rootPath = __dirname, opts = {}) {
return function* (next) {
if (this.method !== 'GET' && this.method !== 'HEAD') {
yield next;
return;
}
// parse url
var url = URL.parse(this.url);
var dir = decodeURIComponent(url.pathname);
// join / normalize from root dir
var path = normalize(join(rootPath, dir));
try {
var info = yield stat(path)
if (!info.isDirectory()) {
return yield next
}
var files = yield readdir(path)
if (opts.filter) {
files = files.filter(function (filename, index) {
return opts.filter(filename, index);
});
}
if (opts.removeHidden) {
files = removeHidden(files)
}
var infos = yield files.map((file) => { return stat(join(path, file)) })
infos = infos.map((info, index) => {
var d = {
name: files[index],
mtime: info.mtime,
type: info.isDirectory() ? 'directory' : 'file'
}
if (!info.isDirectory()) {
d.size = info.size
}
return d
})
this.body = infos;
} catch (e) {
return yield next
}
}
}