grace-rename-file
Version:
按照关键词给路径下的文件修改名称
62 lines (54 loc) • 1.56 kB
JavaScript
var program = require("commander");
const chalk = require("chalk");
const inquirer = require("inquirer");
const fs = require("fs");
var _path = require("path");
program
.version("0.0.1")
.option("-l, --list [list]", "list of customers in CSV file")
.parse(process.argv);
let dir = program.args[0];
const config = [
{
type: "input",
name: "filePath",
message: chalk.green("请输入文件路径:"),
},
{
type: "input",
name: "keyWords",
message: chalk.green("请输入重命名标识:"),
},
];
inquirer.prompt(config).then((config) => {
rename(config);
});
function rename(config) {
fs.readdir(config.filePath.trim(), (err, data) => {
if (err) throw err;
// filter hidden file .DS_Store
const newData = data.filter((item, index) => {
let reg = /^(?=[^\.])/;
return reg.test(item);
});
// saveSuffix name
const suffixList = newData.map((item, index) => {
return getSuffixList(item);
});
newData.forEach((item, index) => {
const withoutSuffix = config.filePath.trim();
let oldPath = _path.join(withoutSuffix, item).split(_path.sep).join("/");
let newPath = `${withoutSuffix}/${config.keyWords}${index}${suffixList[index]}`;
fs.rename(oldPath, newPath.split(_path.sep).join("/"), (err) => {
if (err) throw err;
console.log(chalk.green("success"));
});
});
});
}
// 获取文件后缀 以.结尾
function getSuffixList(str) {
var reg = new RegExp(/\.(\w+)$/);
return reg.exec(str)[0];
}