Files

47 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2026-06-01 23:28:04 +02:00
import { readdir, readFile } from "node:fs/promises";
export const normalizedPublicBaseUrl = (baseUrl) => {
const publicBaseUrl = new URL(baseUrl);
publicBaseUrl.pathname = publicBaseUrl.pathname.endsWith("/")
? publicBaseUrl.pathname
: `${publicBaseUrl.pathname}/`;
return publicBaseUrl.href;
};
export const publicAssetUrl = (baseUrl, publicRelativePath) => {
const encodedPathSegments = publicRelativePath
.split(/[\\/]/u)
.filter(Boolean)
.map(encodeURIComponent)
.join("/");
return new URL(encodedPathSegments, normalizedPublicBaseUrl(baseUrl)).href;
};
export const jsonBuffer = (jsonPayload) =>
Buffer.from(`${JSON.stringify(jsonPayload, null, 2)}\n`, "utf8");
export const optionalJsonDocument = async (jsonPath, fallbackPayload = {}) => {
try {
return JSON.parse(await readFile(jsonPath, "utf8"));
} catch (filesystemError) {
if (filesystemError?.code === "ENOENT") {
return fallbackPayload;
}
throw filesystemError;
}
};
export const readDirectoryEntries = async (inputDirectory) => {
try {
return await readdir(inputDirectory, { withFileTypes: true });
} catch (filesystemError) {
if (filesystemError?.code === "ENOENT") {
return [];
}
throw filesystemError;
}
};