主题
文件批量重命名工具
使用场景
- 一次性处理几十张图片 / 文件
- 文件名是中文或无规则字符串
- 需要统一为 英文 + 序号格式
手动改名既痛苦又浪费时间,用脚本几秒搞定。
rename.js
js
const fs = require('fs');
const path = require('path');
function batchRename(dir, prefix) {
console.log('Batch renaming files in directory:', dir);
const files = fs.readdirSync(dir);
files.forEach((file, index) => {
const ext = path.extname(file);
const oldPath = path.join(dir, file);
const newName = `${prefix}-${String(index+1).padStart(3, '0')}${ext}`;
const newPath = path.join(dir, newName);
fs.renameSync(oldPath, newPath);
console.log(` ${file} -> ${newName}`);
});
}
// 添加命令行参数处理
if (require.main === module) {
// 检查参数数量
if (process.argv.length < 4) {
console.log('使用方法: node rename.js <目录路径> <前缀>');
console.log('示例: node rename.js ./youyuan a');
process.exit(1);
}
const dir = process.argv[2];
const prefix = process.argv[3];
// 检查目录是否存在
if (!fs.existsSync(dir)) {
console.error(`错误: 目录 "${dir}" 不存在`);
process.exit(1);
}
// 执行重命名
try {
batchRename(dir, prefix);
console.log('重命名完成!');
} catch (error) {
console.error('重命名出错:', error.message);
}
}核心思路
- 读取目录下所有文件
- 按顺序生成:
前缀-序号.扩展名 - 直接覆盖原文件名
技术要点
fs.readdirSync:同步读取目录内容,返回文件名数组fs.renameSync:同步重命名/移动文件fs.existsSync:查文件或目录是否存path.extname:提取文件扩展名(包含点号,如 .jpg)path.join:安全拼接路径,自动处理平台差异
使用方式
bash
node rename.js <目录路径> <前缀>示例:
bash
node rename.js ./images img执行后:
原文件名.jpg → img-001.jpg适用场景总结
- 图片资源整理
- 文档批量编号
- 构建前的资源规范化处理