node.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > node.js > Node.js批量替换文件内容

Node.js实现批量替换文件内容示例

作者:郝同学1208

这篇文章主要为大家介绍了Node.js实现批量替换文件内容示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

文章序

将国际化文件中key: value形式改为value: value形式

代码

main.js

const fs = require('fs');
// const args = process.argv;
// console.log(args);
let i18nKeyMap = {};
// const dictnoryMap = new Map([
//   ["components", true],
//   ["hooks", true],
//   ["pages", true],
//   ["store", true],
//   ["utils", true]
// ])
try {
  let fileStr = fs.readFileSync('./source/basic/locale/lang/en.js', 'utf-8');
  // let fileStr = fs.readFileSync('./source/track/locale/lang/en.js', 'utf-8');
  // let fileStr = fs.readFileSync('./source/emap/locale/lang/en.js', 'utf-8');
  fileStr = fileStr.replaceAll(/[\n\r]/g, "").replaceAll(/`/g, "\"").replaceAll(/\/\/[^"'{]*/g, "");
  const leftIndex = fileStr.indexOf('{');
  const rightIndex = fileStr.lastIndexOf('}');
  let innerStr = fileStr.substring(leftIndex + 1, rightIndex).replaceAll(/{/g, "[").replaceAll(/}/g, "]");
  const objStr = "{" + (innerStr[innerStr.length - 1] === "," ?
    innerStr.substring(0, innerStr.length - 1) :
    innerStr) + "}";
  i18nKeyMap = JSON.parse(objStr)
} catch (err) {
  console.log("handle i18n error, the path is: src/locale/lang/en.js");
  console.log("handle i18n error, the reason is: " + err + "\n");
}
handleWorkReplace('./source/basic');
handleDictReplace('./source/basic/locale/lang')
// handleWorkReplace('./source/track');
// handleDictReplace('./source/track/locale/lang')
// handleWorkReplace('./source/emap');
// handleDictReplace('./source/emap/locale/lang')
console.log("执行完毕!")
function handleDictReplace(path) {
  try {
    let fileList = fs.readdirSync(path);
    for (let i = 0; i < fileList.length; i++) {
      replaceDictFile(path + '/' + fileList[i]);
    }
  } catch (err) {
    console.log("handle i18n error, the path is: " + path);
    console.log("handle i18n error, the reason is: " + err + "\n");
  }
}
function handleWorkReplace(path) {
  try {
    let fileList = fs.readdirSync(path);
    let item = null;
    for (let i = 0; i < fileList.length; i++) {
      item = fileList[i];
      const nameList = item.split(".");
      // if (item.indexOf(".") > -1) {
      if (nameList[nameList.length - 1] === "vue" || nameList[nameList.length - 1] === "js") {
        replaceWorkFile(path + '/' + item);
      } else if(item.indexOf(".") === -1) {
        recursionFun(path + "/" + item);
      }
      // } else if (dictnoryMap.has(item)) {
      //   recursionFun(path + "/" + item);
      // }
    }
  } catch (err) {
    console.log("handle i18n error, the path is: " + path);
    console.log("handle i18n error, the reason is: " + err + "\n");
  }
}
function recursionFun(path) {
  try {
    let item = null;
    let fileList = fs.readdirSync(path);
    for (let i = 0; i < fileList.length; i++) {
      item = fileList[i];
      const nameList = item.split(".");
      // if (item.indexOf(".") === -1) {
      //   recursionFun(path + "/" + item);
      // } else {
      //   replaceWorkFile(path + '/' + item);
      // }
      if (nameList[nameList.length - 1] === "vue" || nameList[nameList.length - 1] === "js") {
        replaceWorkFile(path + '/' + item);
      } else if(item.indexOf(".") === -1) {
        recursionFun(path + "/" + item);
      }
    }
  } catch (err) {
    console.log("handle i18n error, the path is: " + path);
    console.log("handle i18n error, the reason is: " + err + "\n");
  }
}
function replaceDictFile(path) {
  try {
    let fileStr = fs.readFileSync(path, 'utf-8');
    for (let key in i18nKeyMap) {
      //language不做处理
      if (key === "language") continue;
      const leftIndex = fileStr.indexOf(key);
      fileStr = fileStr.substring(0, leftIndex) + i18nKeyMap[key] + fileStr.substring(leftIndex + key.length);
    }
    fileStr = fileStr.replaceAll(/\[/g, "{").replaceAll(/\]/g, "}");
    fs.writeFileSync(path, fileStr);
  } catch (err) {
    console.log("handle i18n error, the path is: " + path);
    console.log("handle i18n error, the reason is: " + err + "\n");
  }
}
function replaceWorkFile(path) {
  try {
    let fileStr = fs.readFileSync(path, 'utf-8');
    let writeStream = "";
    let leftIndex = 0;
    let rightIndex = 0;
    for (let i = 0; i < fileStr.length; i++) {
      let preChar = fileStr[i - 1];
      let curChar = fileStr[i];
      let nextChar = fileStr[i + 1];
      let furtherChar = fileStr[i + 2];
      if (curChar === "t" && nextChar === "(" && !/[a-zA-Z0-9]/.test(preChar) && /["'`]/.test(furtherChar)) {
        leftIndex = i + 3;
        for (let j = i + 2; j < fileStr.length; j++) {
          if (/[[${(]/.test(fileStr[j])) {
            console.log("handle i18n error, the path is: " + path);
            console.log("handle i18n error, A part of the line is: " + fileStr.substr(j - 10, 30) + "\n" + "\n");
            for (let k = j + 1; k < fileStr.length; k++) {
              if (fileStr[k + 1] === ")" && /["'`]/.test(fileStr[k])) {
                writeStream += fileStr.substring(i, k + 2);
                i = k + 1;
                break;
              }
            }
            break;
          }
          if (fileStr[j + 1] === ")" && /["'`]/.test(fileStr[j])) {
            rightIndex = j;
            const replaceStr = i18nKeyMap[fileStr.substring(leftIndex, rightIndex)];
            if (!replaceStr) {
              console.log("handle i18n error, the path is: " + path);
              console.log("handle i18n error, the reason is: " + fileStr.substring(leftIndex, rightIndex) + " has no key in en.js!" + "\n");
              writeStream += fileStr.substring(i, j + 2);
              i = j + 1;
              break;
            }
            writeStream += "t(`" + replaceStr + "`)"
            i = j + 1;
            break;
          }
        }
      } else {
        writeStream += fileStr[i];
      }
    }
    fs.writeFileSync(path, writeStream);
  } catch (err) {
    console.log("handle i18n error, the path is: " + path);
    console.log("handle i18n error, the reason is: " + err + "\n");
  }
}

以上就是Node.js实现批量替换文件内容示例的详细内容,更多关于Node.js批量替换文件内容的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文