前言:项目中需要替换文本关键字,但是一个一个的去替换,文件太多了,这时候就想到使用node去批量替换,遍历文件夹及子目录
var fs = require("fs");
var path = require("path");
traverseFolder('test');
function replaceContent(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;
});
});
};
function traverseFolder(folderPath) {
// 读取文件夹列表
const files = fs.readdirSync(folderPath)
// 遍历文件夹列表
files.forEach(function (fileName) {
// 拼接当前文件路径
const filePath = path.join(folderPath, fileName)
// 判断该路径是文件夹还是文件
const stats = fs.statSync(filePath)
if (stats.isDirectory()) {
// 如果是文件夹,递归遍历
traverseFolder(filePath)
console.log('文件夹',filePath)
} else {
// 如果是文件,执行操作
replaceContent(filePath, "taxesCalculation", "taxes_Calculation");
console.log('文件',filePath)
}
})
}