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);
          }
        });
      });
    }
  });
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM