以下是一个简单的示例代码,使用了 Node.js 和 fs 模块来读取 GitBook 书籍的 MD 目录,并将其转换成 JSON 结构。需要注意的是,该代码只能处理最简单的目录结构,对于复杂的结构可能会出现错误。

const fs = require('fs');

function readDirSync(path) {
  const result = [];
  const files = fs.readdirSync(path);
  files.forEach(file => {
    const filePath = `${path}/${file}`;
    const stats = fs.statSync(filePath);
    const isFile = stats.isFile();
    const isDir = stats.isDirectory();
    if (isFile && file.endsWith('.md')) {
      result.push({
        'name': file.replace('.md', ''),
        'path': filePath
      });
    } else if (isDir) {
      result.push({
        'name': file,
        'children': readDirSync(filePath)
      });
    }
  });
  return result;
}

const bookPath = '<gitbook目录路径>';
const bookJson = JSON.stringify(readDirSync(bookPath), null, 2);
console.log(bookJson);

使用方法:

  1. 将上述代码保存到一个 js 文件中,例如 book.js。
  2. 将 GitBook 目录的路径替换掉代码中的 '<gitbook目录路径>'。
  3. 在终端中执行 node book.js
  4. 程序会输出转换后的 JSON 结构。

原文地址: https://www.cveoy.top/t/topic/nid3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录