light-matter
v0.1.2
Published
Create your own front matter parser. Part of the DirectDB project.
Downloads
9
Maintainers
Readme
Light Matter
A dead-simple, minimally-opinionated front matter tool. No baked-in Markdown or YAML handlers. Use light-matter
to construct a custom front matter handler tailored to your needs.
Install
npm i light-matter
# OR
yarn add light-matter
Usage
With a file like this:
---
hello: world
---
# Lorem Ipsum
Dolor sit amet...
Parse it like this:
import lightMatter from 'light-matter'
const { content, frontMatter } = lightMatter.parse(fileText)
console.log(frontMatter)
// "hello: world"
console.log(content)
// "# Lorem Ipsum\n\nDolor sit amet..."
Note that the outputs are still strings. Pass them to the parsers of your choice.
You can also turn them back into the original string input:
lightMatter.stringify({ content, frontMatter })
Complete Example w/ YAML and Markdown
For this example we'll use the following packages:
yaml
- a YAML handler that preserves commentsmarked
- a popular Markdown parserturndown
- an HTML-to-Markdown converter.
We'll wrap these packages in reusable utility functions.
Install
npm i marked turndown yaml
# OR
yarn add marked turndown yaml
Code
import { readFileSync, writeFileSync } from 'fs'
import lightMatter from 'light-matter'
import marked from 'marked'
import TurndownService from 'turndown'
import yaml from 'yaml'
const turndownService = new TurndownService()
function readMarkdownFile(filePath) {
const fileText = readFileSync(filePath, 'utf-8')
const document = lightMatter.parse(fileText)
return {
htmlContent: marked(document.content),
yamlFrontMatter: yaml.parse(document.frontMatter),
}
}
function writeMarkdownFile(filePath, htmlContent, yamlFrontMatter) {
const fileText = lightMatter.stringify({
content: turndownService.turndown(htmlContent),
frontMatter: yaml.stringify(yamlFrontMatter),
})
writeFileSync(filePath, fileText, 'utf-8')
}
TypeScript
The package is written in TypeScript and exports its lone interface:
import { LightMatterDocument } from 'light-matter'
const document: LightMatterDocument = {
content: '# Lorem Ipsum',
frontMatter: 'hello: world',
}
Custom Delimiter
The delimiter defaults to "---"
. Pass a custom delimiter to parse()
or stringify()
as the second argument:
const delimiter = '+++'
lightMatter.parse(fileText, delimiter)
lightMatter.stringify(document, delimiter)
Acknowledgments
Thanks to gray-matter
for inspiration. If it hadn't baked in a YAML parser I didn't want, this package would not exist.