-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06-server.js
48 lines (38 loc) · 1.04 KB
/
06-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
const fs = require('fs')
const express = require('express')
const port = process.env.PORT || 1337
const app = express()
app.get('/', respondText)
app.get('/json', respondJson)
app.get('/echo', respondEcho)
app.get('/static/*', respondStatic)
app.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.json({ text: 'hi', numbers: [1, 2, 3] })
}
function respondEcho (req, res) {
const { input = '' } = req.query
res.json({
normal: input,
shouty: input.toUpperCase(),
characterCount: input.length,
backwards: input
.split('')
.reverse()
.join('')
})
}
function respondStatic (req, res) {
const filename = `${__dirname}/public/${req.params[0]}`
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')
}