-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
43 lines (36 loc) · 1.15 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
'use strict';
var _ = require('lodash'),
fs = require('fs'),
path = require('path'),
send = require('koa-send'),
debug = require('debug')('koa-serve');
module.exports = exports = function (directories, root) {
if (!_.isArray(directories)) directories = [directories];
root = root || path.join(__dirname, '..', '..');
root = path.normalize(root);
return function *(next) {
var reqPath = this.path,
filePath, isAsset, fd;
isAsset = _.any(directories, function (dir) {
return _.startsWith(reqPath, '/' + dir);
});
if (!isAsset) return yield next;
debug('requested:', reqPath);
try {
filePath = (isAsset && !fs.lstatSync(root + this.path).isDirectory())
? root + this.path
: root + this.path + 'index.html';
debug('served:', filePath);
yield send(this, filePath);
}
catch (e) {
debug(e);
if (isAsset) {
this.body = 'Not Found';
this.status = 404;
} else {
yield next;
}
}
}
};