1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | const debug = require('debug')('huncwot:static');
|
15 |
|
16 | const Promise = require('bluebird');
|
17 | const fs = Promise.promisifyAll(require('fs-extra'));
|
18 | const path = require('path');
|
19 | const assert = require('assert');
|
20 | const mime = require('mime-types');
|
21 |
|
22 | function static(root, opts = { index: 'index.html' }) {
|
23 | assert(root, 'you need to specify `root` directory');
|
24 |
|
25 | debug('"%s" %j', root, opts);
|
26 | return async (ctx, next) => {
|
27 | if (ctx.request.method === 'HEAD' || ctx.request.method == 'GET') {
|
28 | try {
|
29 | let file = path.join(root, ctx.request.url);
|
30 | let stats = await fs.statAsync(file);
|
31 |
|
32 | if (stats.isDirectory()) {
|
33 | file = path.join(file, opts.index);
|
34 | stats = await fs.statAsync(file);
|
35 | }
|
36 |
|
37 | let type = path.extname(file);
|
38 |
|
39 | return {
|
40 | statusCode: 200,
|
41 | headers: {
|
42 | 'Content-Type': mime.lookup(type) || 'application/octet-stream',
|
43 | 'Content-Length': stats.size,
|
44 | },
|
45 | body: fs.createReadStream(file)
|
46 | };
|
47 | } catch (error) {
|
48 | return next();
|
49 | }
|
50 | } else {
|
51 | return next();
|
52 | }
|
53 | };
|
54 | }
|
55 |
|
56 | module.exports = static;
|