nodejs批量改文件名
# 批量修改文件名
场景: 需修改一批文件的文件名, 一个个修改太慢了, 不符合程序员的心态
# 上程序
还是程序修改起来方便, 如何修改呢
- 读取文件目录下的文件
- 循环文件,得到具体文件
- 利用fs.rename进行改名
const fs = require("fs");
const path = require("path");
const folderPath = "/Users/xxx/"; // 目录
// 遍历目录得到文件信息
function walk(path, callback) {
var files = fs.readdirSync(path);
files.forEach(function (file,index) {
// 老文件路径
const oldFilePath = folderPath +'/'+ file
// 新文件路径(增加了序号和.)
const newFilePath = folderPath +'/'+ (index+1)+ '.'+ file
rename(oldFilePath, newFilePath)
});
}
walk(folderPath)
// // 修改文件名称
function rename(oldPath, newPath) {
fs.rename(oldPath, newPath, function (err) {
if (err) {
throw err;
}
});
}
上次更新: 2021/12/20, 19:23:10