-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
53 lines (42 loc) · 999 Bytes
/
server.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
52
53
const process = require('./processor')
const config = require('./config')
const debug = require('debug')('app')
const http = require('http')
module.exports = () => {
const server = http.createServer(async (req, res) => {
log(req, res)
const options = parseUrl(req.url)
try {
const result = await process(options)
respond(res, result)
} catch (e) {
respond(res, null)
}
})
server.listen(config.port)
}
const notFound = res => {
res.writeHead(404)
res.end()
}
const log = (req, res) => {
debug(`GET ${req.url}`)
res.on('finish', function () {
debug(res.statusCode == 404 ? '404' : 'OK')
})
}
const parseUrl = url => {
let [_, type, ...path] = url.split('/')
path = path.join('/')
return { type, path }
}
const respond = (res, result) => {
if (!result) {
notFound(res)
return
}
result.on('error', function () {
notFound(res)
})
result.pipe(res)
}