-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
58 lines (50 loc) · 1.62 KB
/
Copy pathserver.js
File metadata and controls
58 lines (50 loc) · 1.62 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
import http from "http";
import fs from "fs";
import path from "path";
import { fileURLToPath } from 'url'
const mimeTypeMap = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml',
'.txt': 'text/plain'
}
/*
Gets the server.js file path, then the directory that server.js lives in (root dir),
then adds /public to the root dir path.
*/
const getPublicDirPath = () => {
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const publicDir = path.join(__dirname, 'public')
return publicDir;
}
const publicDir = getPublicDirPath()
const PORT = 3000
const server = http.createServer((req, res) => {
// prevent directory-traversal
const safeSuffix = path.normalize(req.url).replace(/^(\.\.[\/\\])+/, '')
let fileLoc = path.join(publicDir, safeSuffix)
// if URL ends in slash, serve index.html
if (fileLoc.endsWith(path.sep)) fileLoc += 'index.html'
// if file has no pathname, assume it is a .js file
if (!path.extname(fileLoc)) fileLoc += ".js";
fs.stat(fileLoc, (err, stats) => {
if (err || !stats.isFile()) {
res.writeHead(404, { 'Content-Type': 'text/plain' })
res.end('404 Not Found')
return
}
const ext = path.extname(fileLoc)
const type = mimeTypeMap[ext] || 'application/octet-stream'
res.writeHead(200, { 'Content-Type': type })
fs.createReadStream(fileLoc).pipe(res)
})
})
server.listen(PORT, () => {
console.log(`► Serving ${publicDir} at http://localhost:${PORT}`)
})