最近需要将大量图片重命名 发现重复执行rename脚本之后 图片会消失 原因在于fs.rename异步执行
解决方案如下:
let dirpath = 'img'
async function readDir (path) {
return new Promise(resolve => {
fs.readdir(path, (err, files) => {
if (err) throw err
resolve(files)
})
})
}
async function renameFile (oldName, newName) {
return new Promise(resolve => {
fs.rename(oldName, newName, function (err) {
if (err) throw err
resolve(console.log('suc'))
})
})
}
async function rename (path) {
let files = await readDir(path)
files.map(async (file, index) => {
let oldName = path + '/' + file
let newName = path + '/' + index + file.slice(-4)
await renameFile(oldName, newName)
})
}
rename(dirpath)
网友评论