@paroicms/server
Version:
The ParoiCMS server
59 lines • 2.19 kB
JavaScript
import { isObj } from "@paroicms/public-anywhere-lib";
import mime from "mime";
import { readFile, stat } from "node:fs/promises";
import { join } from "node:path";
export async function serveFile({ req, res }, path, options = {}) {
const { immutable, maxAge, root, on404 } = options;
const fullPath = root ? join(root, path) : path;
try {
let fileStat;
try {
fileStat = await stat(fullPath);
}
catch (err) {
if (isObj(err) && err.code !== "ENOENT" && err.code !== "ENOTDIR")
throw err;
if (on404) {
await on404();
}
else {
res.status(404);
res.send("File not found");
}
return;
}
const lastModified = new Date(fileStat.mtime).toUTCString();
res.append("Last-Modified", lastModified);
if (maxAge !== undefined) {
res.append("Cache-Control", immutable ? `max-age=${maxAge}, immutable` : `max-age=${maxAge}`);
}
const mimeType = mime.getType(fullPath) ?? "application/octet-stream";
const charset = /^text\/|^application\/(javascript|json)/.test(mimeType)
? "; charset=utf-8"
: "";
res.append("Content-Type", `${mimeType}${charset}`);
const ifModifiedSince = req.headers["if-modified-since"];
if (ifModifiedSince) {
const ifModifiedSinceDate = new Date(ifModifiedSince);
const lastModifiedDate = new Date(fileStat.mtime);
lastModifiedDate.setMilliseconds(0);
if (ifModifiedSinceDate >= lastModifiedDate) {
res.status(304).send();
return;
}
}
const buf = await readFile(fullPath);
res.append("X-Content-Type-Options", "nosniff");
res.append("Content-Length", buf.byteLength.toString());
res.status(200);
res.send(buf);
}
catch (error) {
if (isObj(error) && "code" in error) {
if (error.code === "ECONNABORTED")
return;
}
throw error;
}
}
//# sourceMappingURL=serve-file.js.map