-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (65 loc) · 1.67 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
69
70
71
72
73
74
75
76
77
78
79
const { normalize, resolve, parse, sep } = require('node:path');
const resolvePath = require('resolve-path');
const debug = require('debug')('@ladjs/koa-better-static');
const send = require('./send');
module.exports = serve;
/**
* Serve static files from `root`.
*
* @param {String} root
* @param {Object} [opts]
* @return {Function}
* @api public
*/
function serve(root, opts = {}) {
if (typeof root !== 'string') throw new Error('`root` argument missing');
if (opts.maxAge) {
opts.maxage = opts.maxAge;
delete opts.maxAge;
}
const options = {
index: false,
maxage: 0,
hidden: false,
ifModifiedSinceSupport: true,
...opts
};
const normalizedRoot = normalize(resolve(root));
// Options
debug('static "%s" %j', root, opts);
return async function (ctx, next) {
if (ctx.method === 'HEAD' || ctx.method === 'GET') {
let path = ctx.path.slice(parse(ctx.path).root.length);
try {
path = decodeURIComponent(path);
} catch {
ctx.throw('Could not decode path', 400);
return;
}
if (options.index && ctx.path.at(-1) === '/') {
path += options.index;
}
path = resolvePath(normalizedRoot, path);
if (!options.hidden && isHidden(root, path)) {
return;
}
if (await send(ctx, path, options)) {
return;
}
}
return next();
};
}
function isHidden(root, path) {
path = path.slice(root.length).split(sep);
// optimized with `findIndex`
/*
for (let i = 0; i < path.length; i++) {
if (path[i][0] === '.') {
return true;
}
}
return false;
*/
return path.findIndex((segment) => segment[0] === '.') !== -1;
}