UNPKG

@igor.dvlpr/strip-yaml-front-matter

Version:

🦓 Strips YAML front matter from a String or a file. 👾

41 lines (40 loc) • 1.14 kB
// Author: Igor Dimitrijević (@igorskyflyer) import { readFileSync } from 'node:fs'; const yamlFrontMatterRegex = /^---\s*[\s\S]*?\n---\s*/; /** * Strips YAML front matter from a String. * * Example YAML front matter: * * \--- * author: John Doe * publishDate: 27 Aug, 2024 * \--- * * @param content The string whose YAML front matter to strip. * @returns The original String without the YAML front matter. */ export function stripString(content) { if (typeof content !== 'string') { return ''; } return content.replace(yamlFrontMatterRegex, '').trim(); } /** * Strips YAML front matter from a file. * @param path The path to the file. * @throws Will throw an error if the file path is not valid or the file cannot be read. * @returns The original file contents as a String without the YAML front matter. */ export function stripFile(path) { if (typeof path !== 'string') { throw 'No valid path specified.'; } try { const content = readFileSync(path, 'utf-8'); return stripString(content); } catch { throw "Couldn't read the specified file."; } }