-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05-server.js
61 lines (51 loc) · 1.48 KB
/
05-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
54
55
56
57
58
59
60
61
const fs = require('fs')
const http = require('http')
const querystring = require('querystring')
const port = process.env.PORT || 1337
const server = http.createServer(function (req, res) {
if (req.url === '/') return respondText(req, res)
if (req.url === '/json') return respondJson(req, res)
if (req.url.match(/^\/echo/)) return respondEcho(req, res)
if (req.url.match(/^\/static/)) return respondStatic(req, res)
respondNotFound(req, res)
})
server.listen(port)
console.log(`Server listening on port ${port}`)
function respondText (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.end('hi')
}
function respondJson (req, res) {
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ text: 'hi', numbers: [1, 2, 3] }))
}
function respondEcho (req, res) {
const { input = '' } = querystring.parse(
req.url
.split('?')
.slice(1)
.join('')
)
res.setHeader('Content-Type', 'application/json')
res.end(
JSON.stringify({
normal: input,
shouty: input.toUpperCase(),
characterCount: input.length,
backwards: input
.split('')
.reverse()
.join('')
})
)
}
function respondStatic (req, res) {
const filename = `${__dirname}/public${req.url.split('/static')[1]}`
fs.createReadStream(filename)
.on('error', () => respondNotFound(req, res))
.pipe(res)
}
function respondNotFound (req, res) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('Not Found')
}