1 | const fs = require('fs')
|
2 | const url = require('url')
|
3 | const zlib = require('zlib')
|
4 | const path = require('path')
|
5 | const Resp = require('../util/resp')
|
6 |
|
7 | module.exports = conf => (req, resp, next) => {
|
8 | const location = url.parse(decodeURIComponent(req.url))
|
9 | let pathname = path.join(conf.root, location.pathname)
|
10 |
|
11 | if (conf.onRoute) {
|
12 | let routeResult = conf.onRoute(location.pathname, req, resp, {})
|
13 | if (routeResult === false) {
|
14 | return
|
15 | } else {
|
16 | pathname = routeResult ? path.join(conf.root, location.routeResult) : pathname
|
17 | }
|
18 | }
|
19 | const {
|
20 | handleError,
|
21 | handleSuccess,
|
22 | handleNotFound
|
23 | } = Resp(conf)
|
24 |
|
25 | const directory = (pathname, location) =>
|
26 | fs.readdir(pathname, (error, files) => {
|
27 | const base = (location.pathname + '/').replace(/\/+/g, '/')
|
28 | if (error) {
|
29 | handleError(resp, error)
|
30 | } else {
|
31 | let items = ['../'].concat(files.filter(n => !n.match(/^\./)))
|
32 | let html = items
|
33 | .map(name => '<a href="' + url.resolve(base, name) + '">' + name + '</a>')
|
34 | .join('</li><li>')
|
35 | handleSuccess(req, resp, 'html', '<meta charset="utf-8"/> <ul><li>' + html + '</li></ul>')
|
36 | }
|
37 | })
|
38 | fs.stat(pathname, (error, stats) => {
|
39 | if (error) {
|
40 | handleNotFound(resp, pathname)
|
41 | } else if (stats.isFile()) {
|
42 | handleSuccess(req, resp, pathname)
|
43 | let readStream = fs.createReadStream(pathname)
|
44 | if (conf.gzip) {
|
45 | readStream = readStream.pipe(zlib.createGzip())
|
46 | }
|
47 | readStream.pipe(resp)
|
48 | } else if (stats.isDirectory()) {
|
49 | fs.readdir(pathname, (err, files) => {
|
50 | if (err) {
|
51 | handleError(resp, err)
|
52 | } else {
|
53 | directory(pathname, location)
|
54 | }
|
55 | })
|
56 | }
|
57 | })
|
58 | }
|