JavaScript实现批量重命名文件
本文介绍如何使用Node.js的fs模块编写脚本,批量重命名指定文件夹下的图片文件。通过自定义起始编号和文件类型过滤,实现自动化文件名更新,提高文件管理效率。
批量重命名图片脚本
批量重命名图片
在修改下载图片的名称时,逐一手动修改显得过于繁琐,因此编写一个脚本来执行此操作,同时借此机会熟悉Node.js的fs模块。
该脚本旨在一次性对指定文件夹下的多个图片文件进行名称修改与调整,无需逐一手动重命名,从而快速更新文件名并自动执行脚本。
脚本自动处理类似“9a9f0a7f89a7.jpg”的图片,将其重命名为002.jpg格式。
在此示例中,文件重命名从0 ~ 999开始,用户可根据需要命名的图片数量自定义设置起始编号。
reName.js代码如下:
const fs = require("fs");
const path = require("path");
// 要修改的文件路径
const folderPath = "./testPicture";
const imgType = ["jpg", "png", "jpeg", "gif", "bmp", "tiff", "ico", "webp"];
let count = 0;
function pad(num, size) {
let s = num + "";
while (s.length < size) s = "0" + s;
return s;
}
fs.readdir(folderPath, (err, files) => {
try {
if (err) {
console.error("读取文件出错", err);
return;
}
files.forEach((file) => {
// 如果用 path.extname() 获取扩展名,注意名称为空的额外处理
const ext = file.split(".").at(-1).toLowerCase();
if (imgType.includes(ext)) {
const oldFilePath = path.join(folderPath, file);
const newFileName = pad(count, 3) + "." + ext;
const newFilePath = path.join(folderPath, newFileName);
fs.rename(oldFilePath, newFilePath, (err) => {
if (err) console.error("重命名文件出错", err);
});
count++;
}
});
console.log(`重命名完成,共重命名 ${count} 个文件`);
} catch (error) {
throw new Error(error);
}
});
若要修改重命名其他类型的文件,只需修改imgType数组中的文件类型,然后执行脚本即可。
- 执行脚本时,直接使用node命令运行即可,具体命令为
node reName.js。 - 在运行脚本之前,请务必先备份相关文件,以防数据丢失。
其他JavaScript重命名方法补充
方法补充
除了上述方法,本文还整理了一些其他使用JavaScript重命名文件的方法,有需要的读者可以进一步了解。
方法一:
'use strict'
let fs = require('fs');
let args = process.argv;
let dist = 'dist';
let src = 'src';
let index = 0;
let ignore = '';
// 目标路径
dist = args[2];
// 名字前缀
src = args[3];
// 递增后缀
index = args[4] || 1;
// ? 忽略的文件
ignore = args[5] || "";
let files = fs.readdirSync(dist);
let sortValue = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
files.sort(function (a, b) {
let index = -1;
for (let i = sortValue.length - 1; i >= 0; i--) {
index = a.indexOf(sortValue[i]);
if (index != -1) {
// console.log("a: ", a, " i: ", i, " index: ", index);
break;
}
}
if (index == -1) {
return 0;
}
else {
let aid = parseInt(a.substring(index));
let bid = parseInt(b.substring(index));
if (aid == NaN || bid == NaN) {
return 0;
}
else {
return aid - bid;
}
}
});
for (let i = 0; i < files.length; i++) {
if (ignore !== "" && files[i].indexOf(ignore) === -1) {
continue;
}
let stat = fs.statSync(dist + "\\" + files[i]);
let runRename = function (stat) {
if (stat.isFile()) {
let prefix = dist + "\\";
let suffix = files[i].substring(files[i].indexOf("."));
let oldName = prefix + files[i];
let newName = prefix + src + index + suffix;
fs.renameSync(oldName, newName);
index++;
}
};
runRename(stat);
}
方法二:使用JavaScript批量修改文件名的后缀。
在需要修改的文件夹中创建一个js文件,通过node .\****.js命令运行;或者创建一个.bat批处理文件,内容为node .****.js pause,然后双击执行。
请注意修改代码中的dirName变量,以指向正确的目标文件夹。
// 引入 fs 文件系统模块
let fs = require('fs')
const dirName = 'mus' // 读取目标文件夹名称
const reg = /(?<=[.])[a-z]+/ // 文件后缀 匹配规则
// 读文件夹,获取文件名列表
let fileList = fs.readdirSync(dirName)
// 过滤出想要的文件类型
let resultList = fileList.reduce((pev, cur) => {
// 获取后缀
const curPicType = cur.match(reg)[0]
if (['mgg', 'flac', 'ogg', 'lrc'].includes(curPicType)) {
pev.push(cur)
}
return pev
}, [])
console.log('文件列表', resultList)
// 循环当前文件名列表,根据需要重写名字
for (let i = 0; i < resultList.length; i++) {
// 文件完整名称
const curFileName = resultList[i]
// 后缀名
const fileFormat = curFileName.match(reg)[0]
// 去掉后缀的文件名
const fileCode = curFileName.split('.')[0]
// oldPath 原地址
const oldPath = `./${dirName}/${curFileName}`
// newPath 目标地址
let newPath = ''
// 修改方式
// 如果想根据不同条件,将文件分别放到不同的文件夹,按需更改 newPath 即可
if (fileFormat == 'ogg' || fileFormat == 'mgg') {
newPath = `./${dirName}/${fileCode}.mp3`
} else {
newPath = oldPath
}
// 确认修改
fs.rename(oldPath, newPath, (err) => {
if (err) throw err;
console.log(`修改成功 -- ${newPath}`);
})
}
到此这篇关于JavaScript实现批量重命名文件的文章就介绍到这了,更多相关JavaScript重命名文件内容请搜索本站以前的文章或继续浏览下面的相关文章,希望大家以后多多支持本站!
Node.js 安装配置与第一个 HTTP 服务器编写
2026-11-05 11:41:40
怎么使用 nvm 管理并平滑升级 Node.js 版本
2026-11-04 23:15:07
Node.js 怎么使用 zlib 模块解压 gzip 和 deflate
2026-11-03 23:40:50
直接覆盖安装还是用版本管理器?Node.js 升级方式对比
2026-11-03 22:59:07
Express.js 是什么:Node.js Web 框架核心概念与适用场景
2026-11-03 20:00:12
