1
Files
2025/tools/lib/frontmatter.js

54 lines
1.7 KiB
JavaScript

const fs = require("node:fs");
const yaml = require("js-yaml");
const FRONTMATTER_PATTERN = /^---\n([\s\S]*?)\n---\n?/;
/**
* Lit le frontmatter d'un fichier Markdown et retourne son contenu brut.
* La fonction préserve également le corps du fichier afin de permettre
* une réécriture propre après modification.
* @param {string} filePath Chemin absolu du fichier à analyser.
* @returns {{ data: Record<string, any>, body: string, frontmatterText: string, raw: string }|null}
*/
function readFrontmatterFile(filePath) {
const raw = fs.readFileSync(filePath, "utf8");
const match = raw.match(FRONTMATTER_PATTERN);
if (!match) {
return null;
}
const frontmatterText = match[1];
const data = yaml.load(frontmatterText) || {};
const body = raw.slice(match[0].length);
return {
data,
body,
frontmatterText,
raw,
};
}
/**
* Réécrit complètement le fichier Markdown avec un frontmatter mis à jour.
* @param {string} filePath Chemin absolu du fichier.
* @param {Record<string, any>} frontmatter Objet contenant les métadonnées.
* @param {string} body Corps Markdown déjà prêt à être réinséré.
*/
function writeFrontmatterFile(filePath, frontmatter, body) {
if (
typeof frontmatter !== "object" ||
frontmatter === null ||
Array.isArray(frontmatter)
) {
throw new Error(`Frontmatter invalide pour ${filePath}`);
}
const serialized = yaml.dump(frontmatter, { lineWidth: 120, sortKeys: false }).trimEnd();
const contentBody = typeof body === "string" ? body : "";
const rewritten = `---\n${serialized}\n---\n${contentBody}`;
fs.writeFileSync(filePath, rewritten, "utf8");
}
module.exports = {
readFrontmatterFile,
writeFrontmatterFile,
};