递归目录文件夹批量把md文档中的图片转为base64

const fs = require('fs');
const path = require('path');

const dir = './src/file/productVersionFile/';
const dirPath = '/file/productVersionFile/';
//遍历目录得到文件信息
// dir:遍历目录;dirPath用于和根目录拼接
function walk(dir, dirPath) {
  var files = fs.readdirSync(dir);
  files.forEach((file) => {
    let filePath = path.join(__dirname, dirPath, file);
    fs.stat(filePath, (err, stats) => {
      if (err) {
        console.error(err);
        return;
      }
      if (stats.isFile()) {
        let type = path.extname(file);
        if (type === '.md') {
          const data = String(fs.readFileSync(filePath, 'utf8'));
          let re_md_img = /\!\[(.*)\]\((.*)\)/g;
          let md_img_list = data.match(re_md_img);
          let imgList = data.match(/<img.*?(?:>|\/>)/gi);
          let img_url_list = [];
          let imgUrlList = [];
          md_img_list &&
            md_img_list.length > 0 &&
            md_img_list.forEach((item) => {
              if (
                item.includes('![image]') &&
                (item.includes('http://kfront.kedacom.com') ||
                  item.includes('/./file'))
              ) {
                // let img_url = item.match(/(.*)\((.*)\)/)[2];
                let img_url = item.substring(9, item.length - 1);
                img_url_list.push(img_url);
              }
            });
          imgList &&
            imgList.length &&
            imgList.forEach((child) => {
              child.replace(
                /<img [^>]*src=['"]([^'"]+)[^>]*>/gi,
                function (match, capture) {
                  if (child.includes('http://') || child.includes('/./file')) {
                    imgUrlList.push(capture);
                  }
                }
              );
            });
          if (img_url_list.length) {
            // console.log(img_url_list,md_img_list)
            handle(img_url_list, filePath, md_img_list);
          }
          if (imgUrlList.length) {
            // console.log(imgUrlList,imgList)
            handleImg(imgUrlList, filePath, imgList);
          }
        }
      } else if (stats.isDirectory()) {
        let childDir = dir + '/' + file;
        let childDirPath = dirPath + '/' + file;
        walk(childDir, childDirPath);
      }
      //可以访问 `stats` 中的文件属性
    });
  });
}
//遍历替换图片
function handle(data, filePath, imgList) {
  data.forEach((item, index) => {
    let oldImg = item;
    let newImg = item.replace(
      'http://kfront.kedacom.com/file/docImage',
      'D:/GitHub/node-demo/src/static/docImage'
    );
    if (newImg === oldImg) {
      newImg = item.replace(
        'http://kfront.kedacom.com:80/file/docImage',
        'D:/GitHub/node-demo/src/static/docImage'
      );
    }
    if (newImg === oldImg) {
      newImg = item.replace(
        '/./file/docImage',
        `D:/GitHub/node-demo/src/static/docImage`
      );
    }
    const imageData = fs.readFileSync(newImg);
    if (imageData) {
      const imageBase64 = imageData.toString('base64');
      const imagePrefix = 'data:image/jpeg;base64,';
      const imgUrl = imagePrefix + imageBase64;
      replace_readme_info(oldImg, imgUrl, filePath, imgList[index], index);
    }
  });
}
//遍历替换图片
function handleImg(data, filePath, imgList) {
  data.forEach((item, index) => {
    let oldImg = item;
    let newImg = item.replace(
      'http://kfront.kedacom.com/file/docImage/',
      `D:/GitHub/node-demo/src/static/docImage/`
    );
    if (newImg === oldImg) {
      newImg = item.replace(
        'http://kfront.kedacom.com:80/file/docImage',
        `D:/GitHub/node-demo/src/static/docImage/`
      );
    }
    if (newImg === oldImg) {
      newImg = item.replace(
        '/./file/docImage',
        `D:/GitHub/node-demo/src/static/docImage/`
      );
    }
    const imageData = fs.readFileSync(newImg);
    if (imageData) {
      const imageBase64 = imageData.toString('base64');
      const imagePrefix = 'data:image/jpeg;base64,';
      const imgUrl = imagePrefix + imageBase64;
      replace_readme_info(oldImg, imgUrl, filePath, imgList[index], index);
    }
  });
}
//替换md文件内图片
function replace_readme_info(oldImg, newImg, filePath, imgDom, num) {
  // 获取README.md原始信息

  let readme_content = String(fs.readFileSync(filePath, 'utf8'));
  readme_content += `\r\n[id_${num}]:${newImg}`;

  let new_readme_content = readme_content.replace(
    imgDom,
    `\r\n![image][id_${num}]\r\n`
  );

  fs.writeFileSync(filePath, new_readme_content);
}

walk(dir, dirPath);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值