Skip to main content
Deno 2 is finally here 🎉️
Learn more
Go to Latest
The Standard Library has been moved to JSR. See the blog post for details.
function createExtractor
import { createExtractor } from "https://deno.land/std@0.202.0/front_matter/mod.ts";

Factory that creates a function that extracts front matter from a string with the given parsers. Supports YAML, TOML and JSON.

Parameters

formats: Partial<Record<Format, Parser>>

A descriptor containing Format-parser pairs to use for each format.

Returns

A function that extracts front matter from a string with the given parsers.

import { createExtractor, Format, Parser } from "https://deno.land/std@0.202.0/front_matter/mod.ts";
import { assertEquals } from "https://deno.land/std@0.202.0/assert/assert_equals.ts";
import { parse as parseYAML } from "https://deno.land/std@0.202.0/yaml/parse.ts";
import { parse as parseTOML } from "https://deno.land/std@0.202.0/toml/parse.ts";
const extractYAML = createExtractor({ [Format.YAML]: parseYAML as Parser });
const extractTOML = createExtractor({ [Format.TOML]: parseTOML as Parser });
const extractJSON = createExtractor({ [Format.JSON]: JSON.parse as Parser });
const extractYAMLOrJSON = createExtractor({
[Format.YAML]: parseYAML as Parser,
[Format.JSON]: JSON.parse as Parser,
});

let { attrs, body, frontMatter } = extractYAML<{ title: string }>("---\ntitle: Three dashes marks the spot\n---\nferret");
assertEquals(attrs.title, "Three dashes marks the spot");
assertEquals(body, "ferret");
assertEquals(frontMatter, "title: Three dashes marks the spot");

({ attrs, body, frontMatter } = extractTOML<{ title: string }>("---toml\ntitle = 'Three dashes followed by format marks the spot'\n---\n"));
assertEquals(attrs.title, "Three dashes followed by format marks the spot");
assertEquals(body, "");
assertEquals(frontMatter, "title = 'Three dashes followed by format marks the spot'");

({ attrs, body, frontMatter } = extractJSON<{ title: string }>("---json\n{\"title\": \"Three dashes followed by format marks the spot\"}\n---\ngoat"));
assertEquals(attrs.title, "Three dashes followed by format marks the spot");
assertEquals(body, "goat");
assertEquals(frontMatter, "{\"title\": \"Three dashes followed by format marks the spot\"}");

({ attrs, body, frontMatter } = extractYAMLOrJSON<{ title: string }>("---\ntitle: Three dashes marks the spot\n---\nferret"));
assertEquals(attrs.title, "Three dashes marks the spot");
assertEquals(body, "ferret");
assertEquals(frontMatter, "title: Three dashes marks the spot");

({ attrs, body, frontMatter } = extractYAMLOrJSON<{ title: string }>("---json\n{\"title\": \"Three dashes followed by format marks the spot\"}\n---\ngoat"));
assertEquals(attrs.title, "Three dashes followed by format marks the spot");
assertEquals(body, "goat");
assertEquals(frontMatter, "{\"title\": \"Three dashes followed by format marks the spot\"}");