美文网首页
nodejs批量修改文件名

nodejs批量修改文件名

作者: 草珊瑚_6557 | 来源:发表于2023-05-26 13:38 被阅读0次

遍历子目录的所有文件进行修改。通过正则进行匹配文件名。

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

相关文章

网友评论

      本文标题:nodejs批量修改文件名

      本文链接:https://www.haomeiwen.com/subject/ufvkedtx.html