nodejs读取gitbook的summary目录md文件转成json结构
以下是一个使用Node.js读取Gitbook的summary目录md文件并转换为JSON结构的示例代码:
const fs = require('fs');
const path = require('path');
const marked = require('marked');
const SUMMARY_FILE = 'SUMMARY.md';
// 读取summary.md文件内容
const summaryContent = fs.readFileSync(SUMMARY_FILE, 'utf8');
// 将markdown内容转换为HTML
const summaryHtml = marked(summaryContent);
// 将HTML解析为DOM结构
const cheerio = require('cheerio');
const $ = cheerio.load(summaryHtml);
// 解析DOM结构,构建JSON树结构
const summaryJson = [];
let currentLevel = 0;
let currentParent = summaryJson;
$('a').each((i, elem) => {
const href = $(elem).attr('href');
const text = $(elem).text().trim();
if (!href.startsWith('#')) {
const title = text.replace(/^[0-9\.]+/, '').trim();
const level = text.match(/^[0-9\.]+/)[0].split('.').length;
const item = { title, level, href };
const parent = findParent(currentLevel, currentParent, level);
parent.push(item);
currentLevel = level;
currentParent = item.children = [];
}
});
// 查找当前节点的父级节点
function findParent(currentLevel, currentParent, targetLevel) {
if (targetLevel > currentLevel) {
return currentParent[currentParent.length - 1].children;
} else if (targetLevel === currentLevel) {
return currentParent;
} else {
return findParent(currentLevel - 1, currentParent[currentParent.length - 1].children, targetLevel);
}
}
console.log(summaryJson);
该代码使用了以下三个第三方库:
marked将Markdown转换为HTML;cheerio将HTML解析为DOM结构,方便查找节点;path用于处理文件路径。
该代码的主要逻辑如下:
- 读取
SUMMARY.md文件内容; - 将Markdown内容转换为HTML;
- 将HTML解析为DOM结构;
- 遍历所有
a标签,解析出标题、链接和级别等信息; - 根据级别信息构建JSON树结构。
最终输出的JSON结构类似于以下格式:
[
{
"title": "Introduction",
"level": 1,
"href": "README.md",
"children": []
},
{
"title": "Chapter 1",
"level": 1,
"href": "chapter1/README.md",
"children": [
{
"title": "Section 1.1",
"level": 2,
"href": "chapter1/section1.1.md",
"children": []
},
{
"title": "Section 1.2",
"level": 2,
"href": "chapter1/section1.2.md",
"children": []
}
]
}
]
原文地址: https://www.cveoy.top/t/topic/b4BV 著作权归作者所有。请勿转载和采集!