Node.js文件批量重命名工具
Node.js批量重命名工具,支持序号、前缀后缀、正则替换、扩展名修改,带预览模式。
详细内容
// Node.js文件批量重命名工具
// 使用方法: node rename.js <目录> [选项]
// 示例: node rename.js ./images --prefix=img_ --start=1
const fs = require('fs');
const path = require('path');
// 解析命令行参数
function parseArgs() {
const args = process.argv.slice(2);
const options = { dir: '.', prefix: '', suffix: '', start: 1, ext: null, execute: false };
args.forEach(arg => {
if (arg.startsWith('--prefix=')) options.prefix = arg.split('=')[1];
if (arg.startsWith('--suffix=')) options.suffix = arg.split('=')[1];
if (arg.startsWith('--start=')) options.start = parseInt(arg.split('=')[1]);
if (arg.startsWith('--ext=')) options.ext = arg.split('=')[1];
if (arg === '--execute') options.execute = true;
if (!arg.startsWith('--')) options.dir = arg;
});
return options;
}
function batchRename(options) {
const { dir, prefix, suffix, start, ext, execute } = options;
if (!fs.existsSync(dir)) {
console.error('❌ 目录不存在:', dir);
process.exit(1);
}
const files = fs.readdirSync(dir).filter(f => {
return fs.statSync(path.join(dir, f)).isFile();
}).sort();
console.log('========================================');
console.log(' 批量重命名工具');
console.log('========================================');
console.log('目录:', dir);
console.log('文件数:', files.length);
console.log('模式:', execute ? '执行模式' : '预览模式(添加 --execute 执行)');
console.log('----------------------------------------');
let count = 0;
files.forEach((file, index) => {
const extname = path.extname(file);
const basename = path.basename(file, extname);
// 生成新文件名
const num = String(start + index).padStart(3, '0');
let newName = `${prefix}${basename}${suffix}_${num}`;
// 修改扩展名
const newExt = ext ? (ext.startsWith('.') ? ext : '.' + ext) : extname;
const newFile = newName + newExt;
if (file !== newFile) {
console.log(` ${file}`);
console.log(` → ${newFile}`);
console.log('');
if (execute) {
fs.renameSync(
path.join(dir, file),
path.join(dir, newFile)
);
}
count++;
}
});
console.log('----------------------------------------');
console.log(`共处理 ${count} 个文件`);
if (!execute) {
console.log('⚠️ 预览模式,未实际重命名');
console.log(' 添加 --execute 参数执行重命名');
} else {
console.log('✅ 重命名完成!');
}
}
// 运行
const options = parseArgs();
batchRename(options);