42 lines
1.1 KiB
JavaScript
42 lines
1.1 KiB
JavaScript
const fs = require("fs/promises");
|
|
const YAML = require("yaml");
|
|
|
|
const FRONTMATTER_PATTERN = /^---\n([\s\S]*?)\n---\n?/;
|
|
|
|
async function readFrontmatter(filePath) {
|
|
const raw = await fs.readFile(filePath, "utf8");
|
|
const match = raw.match(FRONTMATTER_PATTERN);
|
|
|
|
if (!match) return null;
|
|
|
|
const frontmatterText = match[1];
|
|
const doc = YAML.parseDocument(frontmatterText);
|
|
|
|
if (doc.errors.length) {
|
|
const [error] = doc.errors;
|
|
throw new Error(`Invalid frontmatter in ${filePath}: ${error.message}`);
|
|
}
|
|
|
|
const body = raw.slice(match[0].length);
|
|
|
|
return { doc, body, frontmatterText };
|
|
}
|
|
|
|
async function writeFrontmatter(filePath, doc, body) {
|
|
const serialized = doc.toString().trimEnd();
|
|
const nextContent = `---\n${serialized}\n---\n${body}`;
|
|
|
|
await fs.writeFile(filePath, nextContent, "utf8");
|
|
}
|
|
|
|
function extractRawDate(frontmatterText) {
|
|
const match = frontmatterText.match(/^date:\s*(.+)$/m);
|
|
return match ? match[1].trim() : null;
|
|
}
|
|
|
|
module.exports = {
|
|
extractRawDate,
|
|
readFrontmatter,
|
|
writeFrontmatter,
|
|
};
|