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

 更新时间:2023年08月08日 14:10:13   作者:郝同学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批量替换文件内容的资料请关注脚本之家其它相关文章!

相关文章

  • 从零开始学习Node.js系列教程三:图片上传和显示方法示例

    从零开始学习Node.js系列教程三:图片上传和显示方法示例

    这篇文章主要介绍了Node.js图片上传和显示方法,结合实例形式分析了nodejs基于http传输图片文件及显示图片的相关实现步骤与操作技巧,需要的朋友可以参考下
    2017-04-04
  • Electron调用外接摄像头并拍照上传实现详解

    Electron调用外接摄像头并拍照上传实现详解

    这篇文章主要为大家介绍了Electron调用外接摄像头并拍照上传实例实现详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-02-02
  • Node.js 使用jade模板引擎的示例

    Node.js 使用jade模板引擎的示例

    本篇文章主要介绍了Node.js 使用jade模板引擎的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Linux环境部署node服务并启动详细步骤

    Linux环境部署node服务并启动详细步骤

    最近用node.js开发了一个web项目,下面这篇文章主要给大家介绍了关于Linux环境部署node服务并启动的详细步骤,文中通过图文以及示例代码介绍的非常详细,需要的朋友可以参考下
    2023-05-05
  • nodejs如何解决高并发问题

    nodejs如何解决高并发问题

    这篇文章主要介绍了nodejs如何解决高并发问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-10-10
  • nodejs插件及用法整理

    nodejs插件及用法整理

    在本篇文章里小编给大家整理的是一篇关于nodejs插件及用法相关内容,有兴趣的朋友们可以跟着学习参考下。
    2021-11-11
  • Node.js readline模块与util模块的使用

    Node.js readline模块与util模块的使用

    本篇文章主要介绍了Node.js readline模块与util模块的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-03-03
  • Node.JS段点续传:Nginx配置文件分段下载功能的实现方法

    Node.JS段点续传:Nginx配置文件分段下载功能的实现方法

    在Node.JS中可以配置这个标签来实现文件的分段下载。这篇文章给大家介绍了Node.JS段点续传:Nginx配置文件分段下载功能的实现方法,需要的朋友参考下吧
    2018-03-03
  • 基于Koa(nodejs框架)对json文件进行增删改查的示例代码

    基于Koa(nodejs框架)对json文件进行增删改查的示例代码

    这篇文章主要介绍了基于Koa(nodejs框架)对json文件进行增删改查的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-02-02
  • Node.JS 版本管理工具Fnm安装及配置

    Node.JS 版本管理工具Fnm安装及配置

    本文主要介绍了Node.js版本管理工具Fnm的安装和配置过程,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2024-10-10

最新评论