解决fs.rename重复操作文件消失问题
2018-01-24 本文已影响149人
kate2020
最近需要将大量图片重命名 发现重复执行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)