const fs = require('fs');
const path = require('path');
// 目录路径
const directoryPath = './your-directory';
// 文件名中要替换的字符串
const oldFileNameStr = 'oldFileNameStr';
// 文件名替换后的字符串
const newFileNameStr = 'newFileNameStr';
// 文件内容中要替换的字符串
const oldFileContentStr = 'oldFileContentStr';
// 文件内容替换后的字符串
const newFileContentStr = 'newFileContentStr';
// 读取目录
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
// 检查是否为文件
fs.stat(filePath, (statErr, stats) => {
if (statErr) {
console.error('Error stating file:', statErr);
return;
}
if (stats.isFile()) {
// 读取文件内容
fs.readFile(filePath, 'utf8', (readErr, data) => {
if (readErr) {
console.error('Error reading file:', readErr);
return;
}
// 修改文件内容
const newData = data.replace(oldFileContentStr, newFileContentStr);
// 替换文件名
const newFileName = file.replace(oldFileNameStr, newFileNameStr);
const newFilePath = path.join(directoryPath, newFileName);
// 写入修改后的内容到新文件名的文件
fs.writeFile(newFilePath, newData, 'utf8', (writeErr) => {
if (writeErr) {
console.error('Error writing file:', writeErr);
return;
}
// 删除旧文件
fs.unlink(filePath, (unlinkErr) => {
if (unlinkErr) {
console.error('Error deleting old file:', unlinkErr);
return;
}
console.log(`File ${file} processed successfully.`);
});
});
});
}
});
});
});
关键步骤解释:
- 引入模块:
fs
模块用于文件系统操作,如读取目录、读取文件、写入文件和删除文件。
path
模块用于处理文件路径,确保在不同操作系统上路径处理的一致性。
- 定义参数:
directoryPath
指定要处理的目录路径。
oldFileNameStr
和newFileNameStr
分别是文件名中要替换的旧字符串和新字符串。
oldFileContentStr
和newFileContentStr
分别是文件内容中要替换的旧字符串和新字符串。
- 读取目录:
- 使用
fs.readdir
读取指定目录下的所有文件和子目录名称。如果读取过程出错,打印错误信息并返回。
- 遍历文件:
- 对目录中的每个文件或子目录进行遍历。
- 使用
fs.stat
检查当前项是否为文件。如果是文件,则执行后续操作;如果不是文件(如子目录),则不处理。
- 读取文件内容:
- 使用
fs.readFile
以utf8
编码读取文件内容。如果读取出错,打印错误信息并返回。
- 修改文件内容:
- 使用字符串的
replace
方法将文件内容中的oldFileContentStr
替换为newFileContentStr
。
- 替换文件名:
- 使用字符串的
replace
方法将原文件名中的oldFileNameStr
替换为newFileNameStr
,生成新的文件名。
- 写入新文件:
- 使用
fs.writeFile
将修改后的内容写入新文件名对应的文件。如果写入出错,打印错误信息并返回。
- 删除旧文件:
- 在成功写入新文件后,使用
fs.unlink
删除原文件。如果删除出错,打印错误信息;如果成功删除,打印处理成功的日志。