24 lines
949 B
JavaScript
24 lines
949 B
JavaScript
// Minimal static server for local preview. Run: node serve.js [port]
|
|
const http = require("http");
|
|
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
const ROOT = __dirname;
|
|
const PORT = process.env.PORT || process.argv[2] || 8011;
|
|
const TYPES = {
|
|
".html": "text/html", ".js": "text/javascript", ".css": "text/css",
|
|
".db": "application/octet-stream", ".wasm": "application/wasm",
|
|
".json": "application/json",
|
|
};
|
|
|
|
http.createServer((req, res) => {
|
|
let p = decodeURIComponent(req.url.split("?")[0]);
|
|
if (p === "/") p = "/index.html";
|
|
const file = path.join(ROOT, p);
|
|
if (!file.startsWith(ROOT)) { res.writeHead(403); return res.end(); }
|
|
fs.readFile(file, (err, data) => {
|
|
if (err) { res.writeHead(404); return res.end("Not found"); }
|
|
res.writeHead(200, { "Content-Type": TYPES[path.extname(file)] || "application/octet-stream" });
|
|
res.end(data);
|
|
});
|
|
}).listen(PORT, () => console.log(`http://localhost:${PORT}`));
|