support for stripping off frontmatter

This commit is contained in:
James Brumond 2023-04-29 17:19:34 -07:00
parent 8c33dd7a1a
commit a26588835b
Signed by: james
GPG Key ID: 24BA25B8B303B023
6 changed files with 64 additions and 1 deletions

2
bin/strip-frontmatter Normal file
View File

@ -0,0 +1,2 @@
#!/bin/sh
node $(dirname $0)/strip-frontmatter.js $*

2
bin/strip-frontmatter.js Normal file
View File

@ -0,0 +1,2 @@
#!/usr/bin/env node
require('../build/bin/strip-frontmatter.js');

View File

@ -38,6 +38,28 @@ async function main() {
}
```
### Handling Frontmatter
```ts
import { process_frontmatter } from './build';
const raw_content = `---
title: Example Markdown with Frontmatter
foo:
- bar
- baz
---
# This is some markdown
`;
const { frontmatter, markdown } = process_frontmatter(raw_content);
console.log(frontmatter.title); // "Example Markdown with Frontmatter"
console.log(frontmatter.foo); // [ "bar", "baz" ]
console.log(markdown); // "\n# This is some markdown\n"
```
## Command Line Use
@ -46,6 +68,22 @@ async function main() {
echo '# This is some markdown' | ./bin/markdown2html --base-url 'https://example.com' > output.html
```
### Handling Frontmatter
```bash
filecontents="---
title: Example Markdown with Frontmatter
foo:
- bar
- baz
---
# This is some markdown
"
echo "$filecontents" | ./bin/strip-frontmatter frontmatter.json > markdown.md
```
## Options

View File

@ -0,0 +1,2 @@
console.log('strip-frontmatter');

18
src/frontmatter.ts Normal file
View File

@ -0,0 +1,18 @@
import * as yaml from 'yaml';
export function process_frontmatter(document: string) {
if (! document.startsWith('---\n')) {
return {
frontmatter: null,
markdown: document,
};
}
const endIndex = document.slice(3).indexOf('\n---\n') + 3;
const frontmatterYaml = document.slice(3, endIndex);
const markdown = document.slice(endIndex + 4);
const frontmatter = yaml.parse(frontmatterYaml);
return { frontmatter, markdown };
}

View File

@ -1,2 +1,3 @@
export * from './render';
export { process_frontmatter } from './frontmatter';
export { render_markdown_to_html, MarkdownExtension, MarkdownOptions } from './render';