遍历子目录的所有文件进行修改。通过正则进行匹配文件名。
const fs = require('fs');
const path = require('path');
const PATH = 'c:/testDir/'; // 目录地址
// 遍历目录得到文件信息
function walkSync(currentDirPath, callback) {
fs.readdirSync(currentDirPath, { withFileTypes: true }).forEach(dirent => {
const filePath = path.join(currentDirPath, dirent.name);
if (dirent.isFile()) {
callback(filePath, dirent);
} else if (dirent.isDirectory()) {
walkSync(filePath, callback);
}
});
}
// 修改文件名称
function rename(oldPath, newPath) {
fs.promises.rename(oldPath, newPath).catch(err => {
console.error(`Failed to rename ${oldPath} to ${newPath}`, err);
});
}
// 运行
walkSync(PATH, (filePath, fileName) => {
const oldPath = filePath, // 源文件路径
newPath = filePath.replace(/输入你的正则/, ''); // 新路径
rename(oldPath, newPath);
});
网友评论