Spaces:
Sleeping
Sleeping
File size: 1,034 Bytes
9e69836 | 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 | import http from "node:http";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PUBLIC = path.join(__dirname, "public");
const PORT = Number(process.env.PORT) || 7860;
const MIME = {
".html": "text/html",
".js": "text/javascript",
".css": "text/css",
};
const server = http.createServer((req, res) => {
const urlPath = decodeURIComponent(new URL(req.url, "http://localhost").pathname);
let filePath = path.join(PUBLIC, urlPath === "/" ? "index.html" : urlPath);
if (!filePath.startsWith(PUBLIC)) {
res.writeHead(403).end("Forbidden");
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404).end("Not found");
return;
}
res.writeHead(200, { "Content-Type": MIME[path.extname(filePath)] || "application/octet-stream" });
res.end(data);
});
});
server.listen(PORT, "0.0.0.0", () => {
console.log(`Server listening on port ${PORT}`);
}); |