有的时候我们需要按规律给文件夹下的图片重命名,这时候就只能由请我们的nodjs来帮忙了。
具体实现方式看代码
//使用JS批量修改文件夹下照片名称 具体文件夹路径需要自行配置 配置方法:根据文件存放路径修改第11行代码
const fs = require('fs')
const path = require('path')
// 桌面路径
// const folderPath = `${process.env.USERPROFILE}\\Desktop\\`
// 桌面上某个文件夹的路径
const folderPath = `${process.env.USERPROFILE}\\Desktop\\miniprojectPhoto\\` //${process.env.USERPROFILE}\\Desktop\\`获取桌面路径
// 读取文件夹内所有文件名
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('Error reading folder:', err)
return
}
// 遍历文件列表,重命名文件
files.forEach((file, index) => {
// 确保是照片文件
if (file.toLowerCase().endsWith('.jpg') || file.toLowerCase().endsWith('.jpeg') || file.toLowerCase().endsWith('.png') || file.toLowerCase().endsWith('.gif')) {
const newFileName = `project${index + 1}.jpg`
const oldFilePath = path.join(folderPath, file)
const newFilePath = path.join(folderPath, newFileName)
fs.renameSync(oldFilePath, newFilePath)
console.log(`Renamed ${file} to ${newFileName}`)
}
})
})