all repos — kushiyaki @ 52915bea72a952b70019b646a7c4aaf1addea3ab

🍢 A tiny static site generator for grilling markdown files to perfection

extractFrontmatter.js (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
import { readFile, writeFile } from "fs-extra";
import { unified } from "unified";
import remarkParse from "remark-parse";
import remarkStringify from "remark-stringify";
import remarkFrontmatter from "remark-frontmatter";
import remarkRehype from "remark-rehype";
const yaml = require("js-yaml");
//
//NOTE input: filepath. Output- frontmatter pairs in object
//

export async function extractFrontmatter(filepath) {
  let frontmatterObj;
  const processor = await unified()
    .use(remarkParse)
    .use(remarkStringify)
    .use(remarkFrontmatter, "yaml")
    .use(() => (tree) => {
      frontmatterObj = yaml.load(tree.children[0].value);
      //TODO throw error on invalid frontmatter
      frontmatterObj.filename = filepath.split("/").pop();
      frontmatterObj.filepath = filepath;
    })
    .process(await readFile(filepath, "utf-8"));
  return frontmatterObj;
}

// console.log(await extractFrontmatter("./input/index.md"));