57 lines
2.1 KiB
JavaScript
57 lines
2.1 KiB
JavaScript
import { createReadStream, existsSync, statSync } from "node:fs";
|
|
import { createServer } from "node:http";
|
|
import { extname, resolve, sep } from "node:path";
|
|
|
|
const root = resolve(process.cwd(), "build/client");
|
|
const port = Number.parseInt(process.env.PORT || "3001", 10);
|
|
const host = process.env.HOST || "0.0.0.0";
|
|
const mimeTypes = {
|
|
".css": "text/css; charset=utf-8",
|
|
".html": "text/html; charset=utf-8",
|
|
".ico": "image/x-icon",
|
|
".jpeg": "image/jpeg",
|
|
".jpg": "image/jpeg",
|
|
".js": "text/javascript; charset=utf-8",
|
|
".json": "application/json; charset=utf-8",
|
|
".png": "image/png",
|
|
".svg": "image/svg+xml",
|
|
".webp": "image/webp",
|
|
".woff": "font/woff",
|
|
".woff2": "font/woff2",
|
|
};
|
|
|
|
if (!existsSync(resolve(root, "index.html"))) {
|
|
throw new Error("Production build not found. Run `npm run build` first.");
|
|
}
|
|
|
|
createServer((request, response) => {
|
|
let pathname;
|
|
try {
|
|
pathname = decodeURIComponent(new URL(request.url || "/", "http://localhost").pathname);
|
|
} catch {
|
|
response.writeHead(400).end("Bad request");
|
|
return;
|
|
}
|
|
|
|
const requestedPath = resolve(root, `.${pathname}`);
|
|
const isInsideRoot = requestedPath === root || requestedPath.startsWith(`${root}${sep}`);
|
|
const hasFile = isInsideRoot && existsSync(requestedPath) && statSync(requestedPath).isFile();
|
|
if (!hasFile && (pathname.startsWith("/assets/") || extname(pathname))) {
|
|
response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }).end("Not found");
|
|
return;
|
|
}
|
|
const filePath = hasFile ? requestedPath : resolve(root, "index.html");
|
|
const extension = extname(filePath).toLowerCase();
|
|
|
|
response.setHeader("Content-Type", mimeTypes[extension] || "application/octet-stream");
|
|
response.setHeader(
|
|
"Cache-Control",
|
|
hasFile && pathname.startsWith("/assets/") ? "public, max-age=31536000, immutable" : "no-cache",
|
|
);
|
|
createReadStream(filePath)
|
|
.on("error", () => response.writeHead(500).end("Unable to read build output"))
|
|
.pipe(response);
|
|
}).listen(port, host, () => {
|
|
console.log(`Inogen frontend is available at http://${host}:${port}`);
|
|
});
|