JavaScript 读取 GitBook 书籍目录并转换为 JSON 结构
JavaScript 读取 GitBook 书籍目录并转换为 JSON 结构
本文将介绍如何使用 JavaScript 读取 GitBook 书籍目录中的 Markdown 文件,并将其目录结构转换为 JSON 格式。
目录结构示例
假设 GitBook 书籍目录结构如下:
- Introduction.md
- Chapter 1/
- Section 1.1.md
- Section 1.2.md
- Chapter 2/
- Section 2.1.md
- Section 2.2.md
代码实现
const fs = require('fs');
const path = require('path');
const bookPath = path.join(__dirname, 'book');
function readDir(dirPath) {
const dir = fs.readdirSync(dirPath);
const result = [];
for (let i = 0; i < dir.length; i++) {
const filePath = path.join(dirPath, dir[i]);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
result.push({
'name': dir[i],
'type': 'folder',
'children': readDir(filePath),
});
} else {
if (dir[i].endsWith('.md')) {
result.push({
'name': dir[i].slice(0, -3),
'type': 'file',
});
}
}
}
return result;
}
const book = readDir(bookPath);
console.log(JSON.stringify(book, null, 2));
输出结果
[
{
'name': 'Introduction',
'type': 'file'
},
{
'name': 'Chapter 1',
'type': 'folder',
'children': [
{
'name': 'Section 1.1',
'type': 'file'
},
{
'name': 'Section 1.2',
'type': 'file'
}
]
},
{
'name': 'Chapter 2',
'type': 'folder',
'children': [
{
'name': 'Section 2.1',
'type': 'file'
},
{
'name': 'Section 2.2',
'type': 'file'
}
]
}
]
代码说明
- 使用
fs和path模块读取文件和目录信息。 readDir函数递归遍历目录,并根据文件类型创建 JSON 对象。- 文件名以
.md结尾的为 Markdown 文件,类型为file。 - 文件夹类型为
folder,并包含子目录和文件。 JSON.stringify函数将 JSON 对象转换为字符串输出。
总结
本教程展示了如何使用 JavaScript 读取 GitBook 书籍目录中的 Markdown 文件,并将其目录结构转换为 JSON 格式。该方法可以方便地获取书籍的目录结构,并用于构建网站导航、目录索引等功能。
原文地址: https://www.cveoy.top/t/topic/nieh 著作权归作者所有。请勿转载和采集!