// 重命名
const fs = require("fs")
const path = require("path")
// 修改文件所在的文件夹
var filePath = path.resolve('./');
fileDisplay(filePath)
//文件遍历方法
function fileDisplay(filePath) {
//根据文件路径读取文件,返回文件列表: files
fs.readdir(filePath, (err, files) => {
if (err) {
console.warn(err)
} else {
//遍历读取到的文件列表
files.forEach(filename => {
//获取当前文件的绝对路径
var filedir = path.join(filePath, filename)
//根据文件路径获取文件信息,返回一个fs.Stats对象
fs.stat(filedir, (eror, stats) => {
if (eror) {
console.warn('获取文件stats失败')
} else {
var isFile = stats.isFile() //是文件
var isDir = stats.isDirectory() //是文件夹
if (isFile) {
// 读取文件内容
// var content = fs.readFileSync(filedir, 'utf-8');
// 文件重命名
try {
// 文件名
let fileName = filedir.split('\\').pop()
// 去掉文件中的 567
if (fileName.includes('567')) {
let newPathToFile = fileName.split('567').pop()
newPathToFile = '第' + newPathToFile
let pathList = filedir.split('\\')
pathList.pop()
pathList.push(newPathToFile)
newPathToFile = pathList.join('\\')
fs.renameSync(fileName, newPathToFile)
}
} catch (err) {
// throw err
}
}
if (isDir) {
//递归,如果是文件夹,就继续遍历该文件夹下面的文件
// fileDisplay(filedir)
}
}
})
});
}
});
}
node 文件重命名
于 2021-08-13 15:38:09 首次发布