zoukankan      html  css  js  c++  java
  • node批量修改文件文本内容

    node批量修改文件文本内容,默认会将文件夹下的所有包含指定字符串的文件替换

    想起之前由于公司框架的原因,需要在大量的页面添加重复的动作,所以写这个用来测试玩一下,由于本身操作是不可逆的而且会修改文件夹下的所有内容,所以不要轻易拿去自己的项目使用
    仅供参考,用无关紧要的文件测试通过

    文本内容替换

    执行

    生成结果

    replaceContent.js

    var fs = require("fs");
    var path = require("path");
    
    replaceContent("test", "8888", "<p>666<p>");
    
    function replaceContent(filePath, replacement, substitutes) {
      let replaceFile = function(filePath, sourceRegx, targetStr) {
        fs.readFile(filePath, function(err, data) {
          if (err) {
            return err;
          }
          let str = data.toString();
          str = str.replace(sourceRegx, targetStr);
          fs.writeFileSync(filePath, str, function(err) {
            if (err) return err;
          });
        });
      };
    
      //遍历test文件夹
      fs.readdir("./" + filePath + "", function(err, files) {
        if (err) {
          return err;
        }
        if (files.length != 0) {
          files.forEach((item) => {
            let path = "./" + filePath + "/" + item;
            //判断文件的状态,用于区分文件名/文件夹
            fs.stat(path, function(err, status) {
              if (err) {
                return err;
              }
              let isFile = status.isFile(); //是文件
              let isDir = status.isDirectory(); //是文件夹
    
              if (isFile) {
                replaceFile(path, replacement, substitutes);
                console.log("修改路径为:" + path + "文件成功");
              }
    
              if (isDir) {
                console.log("文件夹:" + item);
              }
            });
          });
        }
      });
    }
    
    
    愿以往所学皆有所获
  • 相关阅读:
    EZOJ #202
    EZOJ #201
    p5156 [USACO18DEC]Sort It Out
    p4363 [九省联考2018]一双木棋chess
    p2150 [NOI2015]寿司晚宴
    p5155 [USACO18DEC]Balance Beam
    p2414 [NOI2011]阿狸的打字机
    实验室断网的解决方案
    人需要看到未来
    门德尔松--罗辑思维
  • 原文地址:https://www.cnblogs.com/Azune/p/14378193.html
Copyright © 2011-2022 走看看