跳到主要内容

文件名

2023年01月31日
柏拉文
越努力,越幸运
前言

**通过Node实现批量修改文件名

实现

const fs = require("fs");
const Path = require("path");
const chalk = require("chalk");
const Inquirer = require("inquirer");

const targetDirOptions = [
{
name: "test",
value: {
path: "./test",
suffix: "(js|ts)",
},
}
];

const selectTargetDir = () => {
return new Promise((resolve, reject) => {
const questionList = [
{
type: "list",
name: "value",
choices: targetDirOptions,
message: "请选择一个文件夹:",
validate(val) {
if (val === "") return "必须选择文件夹!";
return true;
},
},
];
Inquirer.prompt(questionList).then((answers) => {
resolve(answers.value);
});
});
};
const inputTargetName = () => {
return new Promise((resolve) => {
const questionList = [
{
type: "input",
name: "value",
message: "请输入命名前缀:",
},
];
Inquirer.prompt(questionList).then((answers) => {
resolve(answers.value);
});
});
};
const readDir = (targetPath) => {
return new Promise((resolve) => {
fs.readdir(targetPath, (err, files) => {
if (err) throw err;
resolve(files);
});
});
};
const renameFile = (oldPath, newPath) => {
return new Promise((resolve) => {
fs.rename(oldPath, newPath, (err) => {
if (err) {
throw err;
}
resolve();
});
});
};
const rename = (file, targetName) => {
return new Promise(async (resolve) => {
try {
const rootPath = process.cwd();
const reg = new RegExp(`.*(\.${file.suffix})`, "i");
const targetPath = Path.resolve(rootPath, file.path);
const resultFileList = await readDir(targetPath);
const fileList = resultFileList.filter((filename) => {
return reg.test(filename);
});
for (let index = 0; index < fileList.length; index++) {
let value = fileList[index];
let newPathFileName = value.replace(reg, targetName + index + "$1");
let result = fileList.includes(newPathFileName);
if (result) {
return reject("不可与之前命名相同!请重新命名");
}
}
for (let index = 0; index < fileList.length; index++) {
let value = fileList[index];
let oldPath = targetPath + "/" + value;
let newPathFileName = value.replace(reg, targetName + index + "$1");
let newPath = targetPath + "/" + newPathFileName;
await renameFile(oldPath, newPath);
}
resolve();
} catch (error) {
reject(error);
}
});
};

async function main() {
try {
const resultFile = await selectTargetDir();
const resultName = await inputTargetName();
const initFileName = Date.now();
await rename(resultFile, initFileName);
await rename(resultFile, resultName);
console.log(`${chalk.green("✨✨✨重命名成功!")}`);
} catch (error) {
console.log(`${chalk.yellow("✨✨✨重命名失败!")}`);
console.log(`${chalk.blue("失败原因为:")}${chalk.magenta(resultRename)}`);
}
}

main();