-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (54 loc) · 1.82 KB
/
server.js
File metadata and controls
66 lines (54 loc) · 1.82 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
60
61
62
63
64
65
66
const http = require("node:http");
const fs = require("node:fs/promises");
const path = require("node:path");
const HOST = process.env.HOST || "127.0.0.1";
const PORT = Number(process.env.PORT || 4173);
const ROOT = __dirname;
const CONTENT_TYPES = {
".css": "text/css; charset=utf-8",
".csv": "text/csv; charset=utf-8",
".html": "text/html; charset=utf-8",
".ico": "image/x-icon",
".js": "text/javascript; charset=utf-8",
".json": "application/json; charset=utf-8",
".png": "image/png",
".svg": "image/svg+xml; charset=utf-8",
};
function resolvePath(urlPath) {
const pathname = decodeURIComponent(urlPath.split("?")[0]);
const target = pathname === "/" ? "/index.html" : pathname;
const absolutePath = path.normalize(path.join(ROOT, target));
if (!absolutePath.startsWith(ROOT)) {
return null;
}
return absolutePath;
}
async function serveFile(filePath, response) {
const extension = path.extname(filePath).toLowerCase();
const contentType = CONTENT_TYPES[extension] || "application/octet-stream";
const file = await fs.readFile(filePath);
response.writeHead(200, { "content-type": contentType });
response.end(file);
}
const server = http.createServer(async (request, response) => {
const filePath = resolvePath(request.url || "/");
if (!filePath) {
response.writeHead(403, { "content-type": "text/plain; charset=utf-8" });
response.end("Forbidden");
return;
}
try {
const stats = await fs.stat(filePath);
if (stats.isDirectory()) {
await serveFile(path.join(filePath, "index.html"), response);
return;
}
await serveFile(filePath, response);
} catch {
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
response.end("Not found");
}
});
server.listen(PORT, HOST, () => {
console.log(`Serving http://${HOST}:${PORT}`);
});