54 lines
1.7 KiB
JavaScript
54 lines
1.7 KiB
JavaScript
const http = require("http");
|
|
const { readFile, stat } = require("fs");
|
|
const { extname, join, normalize } = require("path");
|
|
|
|
const port = process.env.PORT || 3000;
|
|
const public_dir = join(__dirname, "public");
|
|
const mime_types = {
|
|
".html": "text/html; charset=UTF-8",
|
|
".css": "text/css; charset=UTF-8",
|
|
".js": "application/javascript; charset=UTF-8",
|
|
".json": "application/json; charset=UTF-8",
|
|
".svg": "image/svg+xml",
|
|
".woff": "font/woff",
|
|
".woff2": "font/woff2",
|
|
".ttf": "font/ttf",
|
|
".png": "image/png",
|
|
".jpg": "image/jpeg",
|
|
".jpeg": "image/jpeg",
|
|
".ico": "image/x-icon"
|
|
};
|
|
|
|
const safe_path = (url_path) => {
|
|
if (!url_path || url_path === "/") return join(public_dir, "index.html");
|
|
const cleaned = normalize(url_path).replace(/^(\.\.([/\\]|$))+/, "");
|
|
return join(public_dir, cleaned);
|
|
};
|
|
|
|
const send = (file_path, res) => {
|
|
readFile(file_path, (err, data) => {
|
|
if (err?.code === "ENOENT") {
|
|
res.writeHead(404, { "Content-Type": "text/plain; charset=UTF-8" });
|
|
res.end("404 not found");
|
|
return;
|
|
}
|
|
if (err) {
|
|
res.writeHead(500, { "Content-Type": "text/plain; charset=UTF-8" });
|
|
res.end("500 internal server error");
|
|
return;
|
|
}
|
|
const type = mime_types[extname(file_path).toLowerCase()] || "application/octet-stream";
|
|
res.writeHead(200, { "Content-Type": type });
|
|
res.end(data);
|
|
});
|
|
};
|
|
|
|
http
|
|
.createServer((req, res) => {
|
|
const file_path = safe_path((req.url || "/").split("?")[0]);
|
|
stat(file_path, (err, info) => send(!err && info.isDirectory() ? join(file_path, "index.html") : file_path, res));
|
|
})
|
|
.listen(port, () => {
|
|
console.log(`web running at http://localhost:${port}`);
|
|
});
|