-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstatic-file.js
51 lines (45 loc) · 1.15 KB
/
static-file.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
const url = require('url')
const fs = require('fs')
const path = require('path')
const mime = require('mime/lite')
function createStaticFileHandler (baseDir) {
return (req, res, next) => {
let reqURL = url.parse(req.url)
let localPath = baseDir + path.normalize(reqURL.pathname)
fs.stat(localPath, (err, stats) => {
if (err) {
notFound()
} else {
if (stats.isDirectory()) {
serve(`${localPath}/index.html`)
} else {
serve(localPath)
}
}
})
function notFound () {
if (next) {
next(req, res)
} else {
res.writeHead(404)
res.end('not found')
}
}
function serve (aPath) {
const mimeType = mime.getType(aPath)
const stream = fs.createReadStream(aPath, { bufferSize: 64 * 1024 })
stream.pipe(res)
stream.on('open', () => {
if (mimeType) {
res.setHeader('Content-type', mimeType)
} else {
res.setHeader('Content-type', 'application/octet-stream')
}
})
stream.on('error', e => {
notFound()
})
}
}
}
module.exports = createStaticFileHandler