-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest-server.js
More file actions
59 lines (53 loc) · 1.4 KB
/
test-server.js
File metadata and controls
59 lines (53 loc) · 1.4 KB
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
// Simple static file server
// node server.js (portNumber)
var http = require("http")
var fs = require("fs")
var path = require("path")
const port = process.argv[2] || 3000
const home = __dirname
const extToType = {
".ico": "image/x-icon",
".html": "text/html",
".js": "text/javascript",
".json": "application/json",
".css": "text/css",
".png": "image/png",
".jpg": "image/jpeg",
".wav": "audio/wav",
".mp3": "audio/mpeg",
".svg": "image/svg+xml",
".pdf": "application/pdf",
".doc": "application/msword",
}
const server = http.createServer((req, res) => {
console.log(
`${new Date().toLocaleTimeString([], {
hour: "numeric",
minute: "2-digit",
second: "numeric",
fractionalSecondDigits: 2,
})} - ${req.method}: ${req.url}`
)
try {
const filePath = path.join(home, req.url === "/" ? "index.html" : req.url)
const extname = path.extname(filePath)
const contentType = extToType[extname]
fs.readFile(filePath, (err, data) => {
if (!err) {
res.writeHead(200, {
...(contentType && { "Content-Type": contentType }),
})
res.end(data)
} else {
res.writeHead(404)
res.end(`404 ${filePath} not found`)
}
})
} catch (err) {
res.writeHead(500)
res.end(`500 server error: ${err}`)
}
})
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`)
})