UNPKG

1.77 kBJavaScriptView Raw
1// Copyright 2017 Zaiste & contributors. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14const debug = require('debug')('huncwot:static');
15
16const Promise = require('bluebird');
17const fs = Promise.promisifyAll(require('fs-extra'));
18const path = require('path');
19const assert = require('assert');
20const mime = require('mime-types');
21
22function 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
56module.exports = static;