function createExtractor
createExtractor(formats: Partial<Record<"yaml" | "toml" | "json" | "unknown", Parser>>): ExtractorFactory that creates a function that extracts front matter from a string with the given parsers. Supports YAML, TOML and JSON.
Parameters
formats: Partial<Record<"yaml" | "toml" | "json" | "unknown", Parser>>A descriptor containing Format-parser pairs to use for each format.
Return Type
A function that extracts front matter from a string with the given parsers.
import { createExtractor, Parser } from "@std/front-matter"; import { assertEquals } from "@std/assert/assert_equals"; import { parse as parseYAML } from "@std/yaml/parse"; import { parse as parseTOML } from "@std/toml/parse"; const extractYAML = createExtractor({ yaml: parseYAML as Parser }); const extractTOML = createExtractor({ toml: parseTOML as Parser }); const extractJSON = createExtractor({ json: JSON.parse as Parser }); const extractYAMLOrJSON = createExtractor({ yaml: parseYAML as Parser, 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\"}");