Logo

node 批量提取 markdown 标题

NodeJS

FrontEnd-Replay 内部有很多子项目,不想一个个打开找标题,就写了这个脚本,用来批量提取标题。同理这个脚本也可以用于提取其他信息。

刚开始我是使用的 console 直接在控制台打印。遇到一个问题,中括号 []会丢失,是被转义的原因吗?

于是,我尝试把字符串输出成文件,这样就没问题了。

后续可以优化输出树形的 markdown 路径,因为里面有很多子项目,这样可以方便查找。

使用方法:

  1. folderPath 为需要提取标题的文件夹路径
  2. 运行一下 node index.js 即可输出标题和路径
const fs = require('fs');
const path = require('path');
let str = ''
const folderPath = '../../FEE'; // 替换成需要读取的文件夹路径

function readMarkdownFiles(dirPath) {
  fs.readdir(dirPath, (err, files) => {
    if (err) {
      console.error(err);
      return;
    }

    files.forEach(file => {
      const filePath = path.join(dirPath, file);
      fs.stat(filePath, (err, stats) => {
        if (err) {
          console.error(err);
          return;
        }

        if (stats.isDirectory() && file !== 'node_modules') {
          readMarkdownFiles(filePath);
        } else if (stats.isFile() && path.extname(file).toLowerCase() === '.md') {
          const stream = fs.createReadStream(filePath);
          let firstLine = '';
          stream.on('data', chunk => {
            const firstNewLineIndex = chunk.indexOf('\n');
            if (firstNewLineIndex !== -1) {
              firstLine += chunk.slice(0, firstNewLineIndex);
              stream.close();
            } else {
              firstLine += chunk;
            }
          });
          stream.on('close', () => {
            let title = firstLine.replace(/#/g, '');
            let fileText = filePath.replace(/..\\..\\/, '')
            str += `[${title}](${fileText})` + '\r\n'

            fs.writeFile('./link.markdown', str.replace("/\\\\/g","\\/"), err => {
              if (err) {
                console.error(err)
                return
              }
              console.error('输出成功!')
              //文件写入成功。
            })
          });
        }
      });
    });
  });
}

readMarkdownFiles(folderPath);