js-yaml 提取 markdown 中的 front-matter
2025/9/28...小于 1 分钟
js-yaml 提取 markdown 中的 front-matter
为了让我的博客自动生成排序,我在 markdown 中的 front-matter 里加入了 sort 字段,在编译自动生成侧边栏时需要读取这个字段,使用 js-yaml
提取信息,使用如下:
引入依赖
pnpnm install js-yaml
导包
import yaml from "js-yaml"
import fs from 'fs'
// 使用
const content = fs.readFileSync(myPath + file + ".md", 'utf8')
let re = /---(.*?)---/sg
let s = re.exec(content)[1]
console.log(`处理 ${myPath + file} 排序`)
let frontMatter = yaml.load(s)
console.log(frontMatter)
我这里版本使用的是 4.1.0
load 方法已经安全,在旧一些的版本使用使用
const fs = require('fs')
const content = fs.readFileSync(myPath + file + ".md", 'utf8')
let re = /---(.*?)---/sg
const yaml = require('js-yaml');
let s = re.exec(content)[1]
console.log(yaml.safeLoad(s))
提取结果
markdown 中的 front-matter 示例
---
title: js-yaml 提取 markdown 中的 front-matter
category:
tag:
date: 2025-09-28
create_date: 2025-09-28 10:55
sort: 20
---
提取结果
{
title: 'js-yaml 提取 markdown 中的 front-matter',
category: null,
tag: null,
date: 2025-09-28T00:00:00.000Z,
create_date: '2025-09-28 10:55',
sort: 20
}