将指定文件的中文字符串,输出到特定的文件夹

项目根目录,创建一个文件util.js,内容如下:
const path = './src' // 文件夹地址
const outerFileName = './src/locales/zh-CN.ts' // 输出文件
const outFile=['.umi', 'locales', 'utils']// 需要排除的文件夹
const fs = require('fs')

try {
  const filePathArr = []
  // 递归获取所有文件路径(ts、tsx)
  function getAllFilesPath(path) {
    const files = fs.readdirSync(path).filter(file => !outFile.includes(file));
    files.forEach((file) => {
      const filePath = `${path}/${file}`;
      if (/\.tsx?$/.test(file)) { // 检查文件是否以 .ts 或 .tsx 结尾
        if (!/\/locales\//.test(filePath)) { // 检查文件路径是否包含 locales 目录
          filePathArr.push(filePath);
        }
      } else if (fs.statSync(filePath).isDirectory()) {
        getAllFilesPath(filePath); // 递归处理子目录
      }
    });
  }

  getAllFilesPath(path)
  // 遍历所有的文件,提取其中的中文字符串
  const chineseWords = [];
  filePathArr.forEach((filePath) => {
    const fileContent = fs.readFileSync(filePath, 'utf8');
    const contentWithoutComments = removeComments(fileContent);
    const matches = contentWithoutComments.match(/[\u4e00-\u9fa5\s]+/g); // 匹配中文字符和空格
    if (matches) {
      matches.forEach((match) => {
        const trimmedMatch = match.trim(); // 去除首尾空格
        if (trimmedMatch !== '' && !chineseWords.includes(trimmedMatch)) {
          chineseWords.push(trimmedMatch);
        }
      });
    }
  });
  // 将中文字符串按照 locales 文件的格式输出到 ts 文件
   // 将中文字符串写入 ts 文件
   let outputString = 'export default {\n';
   chineseWords.forEach((word) => {
     outputString += `  "${word}": "${word}",\n`;
   });
   outputString += '};\n';
  // 将中文字符串写入 ts 文件
  fs.writeFileSync(outerFileName, outputString);
  console.debug('输出 JSON 文件成功:', outerFileName);

  // 去除注释函数
  function removeComments(content) {
    return content.replace(/(\/\*[\s\S]*?\*\/)|(\/\/.*$)/gm, '');
  }
} catch (err) {
  console.debug(err)
}

最后再执行node -util.js命令就可以看到指定文件夹目录下生成的数据了

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值