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批量替换文件内容的资料请关注脚本之家其它相关文章!

相关文章

  • 用C/C++来实现 Node.js 的模块(二)

    用C/C++来实现 Node.js 的模块(二)

    上篇文章的主要内容讲诉了用C/C++来实现 Node.js 的模块,本文更深一步继续探讨这个问题,有需要的朋友可以参考下
    2014-09-09
  • Node.js基础入门之回调函数及异步与同步详解

    Node.js基础入门之回调函数及异步与同步详解

    Node.js是一个基于Chrome V8引擎的JavaScript运行时。类似于Java中的JRE,.Net中的CLR。本文将详细为大家介绍Node.js中的回调函数及异步与同步,感兴趣的可以了解一下
    2022-03-03
  • 基于 Node.js 实现前后端分离

    基于 Node.js 实现前后端分离

    为了解决传统Web开发模式带来的各种问题,我们进行了许多尝试,但由于前/后端的物理鸿沟,尝试的方案都大同小异。痛定思痛,今天我们重新思考了“前后端”的定义,引入前端同学都熟悉的NodeJS,试图探索一条全新的前后端分离模式。
    2016-04-04
  • Node ORM项目中使用Sequelize实例详解

    Node ORM项目中使用Sequelize实例详解

    这篇文章主要为大家介绍了Node ORM项目中使用Sequelize实例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-04-04
  • 快速搭建Node.js(Express)用户注册、登录以及授权的方法

    快速搭建Node.js(Express)用户注册、登录以及授权的方法

    这篇文章主要介绍了快速搭建Node.js(Express)用户注册、登录以及授权,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-05-05
  • 详解如何查看node端口被占用并杀死

    详解如何查看node端口被占用并杀死

    这篇文章主要给大家介绍了如何查看node端口被占用并杀死,文中给出了相关的解决方法,并通过代码示例给大家介绍的非常详细,对前端开发要学会如何查看端口占用并杀死非常有用,需要的朋友可以参考下
    2024-01-01
  • NodeJs爬虫框架Spider基础使用教程

    NodeJs爬虫框架Spider基础使用教程

    这篇文章主要为大家介绍了NodeJs爬虫框架Spider基础使用教程,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-07-07
  • Node.js16.15.1的一个报错以及解决方案分享

    Node.js16.15.1的一个报错以及解决方案分享

    这篇文章主要给大家介绍了关于Node.js16.15.1的一个报错以及解决方案的相关资料,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2022-12-12
  • 利用Decorator如何控制Koa路由详解

    利用Decorator如何控制Koa路由详解

    最近学习了plover的底层框架koa,所以下面这篇文章主要给大家介绍了关于利用Decorator如何控制Koa路由的相关资料,,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴,下面来随着小编一起学习学习吧
    2018-06-06
  • nodejs搭建本地服务器并访问文件操作示例

    nodejs搭建本地服务器并访问文件操作示例

    这篇文章主要介绍了nodejs搭建本地服务器并访问文件操作,结合实例形式分析了nodejs搭建本地服务器操作步骤及文件访问相关实现技巧,需要的朋友可以参考下
    2019-05-05

最新评论