Commit 8f86e169 by PLN (Algolia)

serve-out: static preview with nginx-like clean URLs (try_files uri uri.html) —…

serve-out: static preview with nginx-like clean URLs (try_files uri uri.html) — python http.server cannot, it serves directory listings
parent 103e6fca
#!/usr/bin/env node
/**
* Static preview of the `out/` export with nginx-like clean URLs
* (`try_files $uri $uri.html $uri/`): /les-femmes/emilie-du-chatelet
* resolves to les-femmes/emilie-du-chatelet.html. `python3 -m http.server`
* does NOT do this (directory listing ahah). Loopback-only, like prod nginx.
*
* Usage: PORT=17008 node scripts/serve-out.mjs
*/
import { createServer } from "node:http";
import { stat, readFile } from "node:fs/promises";
import path from "node:path";
const ROOT = path.resolve(import.meta.dirname, "..", "out");
const PORT = Number(process.env.PORT || 17008);
const MIME = {
".html": "text/html; charset=utf-8",
".txt": "text/plain; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".webp": "image/webp",
".svg": "image/svg+xml",
".woff2": "font/woff2",
".ico": "image/x-icon",
};
async function tryFile(rel) {
const abs = path.join(ROOT, path.normalize(rel).replace(/^([/\\]|\.\.)+/, ""));
try {
const st = await stat(abs);
if (!st.isFile()) return null;
return { abs, buf: await readFile(abs) };
} catch {
return null;
}
}
createServer(async (req, res) => {
let p = decodeURIComponent(new URL(req.url, "http://x").pathname);
if (p.endsWith("/")) p += "index.html";
// nginx: try_files $uri $uri.html $uri/
for (const candidate of [p, `${p}.html`, `${p.replace(/\.html$/, "")}/index.html`]) {
const hit = await tryFile(candidate);
if (hit) {
res.writeHead(200, {
"content-type": MIME[path.extname(hit.abs)] ?? "application/octet-stream",
"cache-control": "no-store",
});
res.end(hit.buf);
return;
}
}
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
res.end("404");
}).listen(PORT, "127.0.0.1", () => {
console.log(`serve-out: http://127.0.0.1:${PORT} (root ${ROOT})`);
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment