js读取gitbook书籍目录的md文件将里面的目录结构转成json结构
以下是一个简单的实现,假设目录结构如下:
- 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"
}
]
}
]
原文地址: https://www.cveoy.top/t/topic/bURl 著作权归作者所有。请勿转载和采集!