File size: 1,078 Bytes
381b90d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createServer } from "node:http";
import { extname, join, normalize } from "node:path";
const port = Number(process.env.PORT || process.argv[2] || 8000);
const root = process.cwd();
const types = { ".html": "text/html", ".mjs": "text/javascript", ".md": "text/markdown" };
createServer(async (request, response) => {
const pathname = new URL(request.url || "/", "http://fixture.local").pathname;
const relative = pathname === "/" ? "index.html" : normalize(pathname).replace(/^[/\\]+/, "");
const target = join(root, relative);
if (!target.startsWith(root)) return response.writeHead(403).end("Forbidden");
try {
const info = await stat(target);
if (!info.isFile()) throw new Error("not a file");
response.writeHead(200, { "Content-Type": types[extname(target)] || "application/octet-stream" });
createReadStream(target).pipe(response);
} catch {
response.writeHead(404).end("Not found");
}
}).listen(port, "0.0.0.0", () => console.log(`fixture ready on ${port}`));
|