sitegen/framework/mime.ts

31 lines
935 B
TypeScript

const entries = fs.readFileSync(
path.join(import.meta.dirname, "mime.txt"),
"utf8",
)
.split("\n")
.map((line) => line.trim())
.filter((line) => line && !line.startsWith("#"))
.map((line) => line.split(/\s+/, 2) as [string, string]);
const extensions = new Map(entries.filter((x) => x[0].startsWith(".")));
const fullNames = new Map(entries.filter((x) => !x[0].startsWith(".")));
/**
* Accepts:
* - Full file path or basename
* - Extension (with or without dot)
*/
export function contentTypeFor(file: string) {
const slash = file.indexOf("/");
if (slash !== -1) file = file.slice(slash + 1);
const dot = file.indexOf(".");
if (dot === -1) file = "." + file;
else if (dot > 0) {
let entry = fullNames.get(file);
if (entry) return entry;
file = file.slice(dot);
}
return extensions.get(file) ?? "application/octet-stream";
}
import * as fs from "./fs.ts";
import * as path from "node:path";