Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (47 loc) · 1.38 KB
/
Copy pathserver.js
File metadata and controls
56 lines (47 loc) · 1.38 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
const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = process.env.PORT || 3000;
const ROOT = __dirname;
const MIME_TYPES = {
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
".json": "application/json",
".ico": "image/x-icon",
".svg": "image/svg+xml",
};
function sendText(res, status, content, type = "text/plain") {
res.writeHead(status, {
"Content-Type": type,
});
res.end(content);
}
const server = http.createServer((req, res) => {
const requestUrl = new URL(req.url, `http://${req.headers.host || "localhost"}`);
if (requestUrl.pathname === "/favicon.ico") {
sendText(res, 204, "");
return;
}
const requestedPath = requestUrl.pathname === "/"
? "/index.html"
: decodeURIComponent(requestUrl.pathname);
const safePath = path.normalize(requestedPath).replace(/^\.\./, "");
const filePath = path.join(ROOT, safePath);
if (!filePath.startsWith(ROOT)) {
sendText(res, 403, "Forbidden");
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
sendText(res, 404, "Not Found");
return;
}
const ext = path.extname(filePath).toLowerCase();
const type = MIME_TYPES[ext] || "application/octet-stream";
sendText(res, 200, data, type);
});
});
server.listen(PORT, () => {
console.log(`Focus Reader running at http://localhost:${PORT}`);
});