nodejs異步刪除非空文件

nodejs異步刪除非空文件node

const fs = require('fs')
const path = require('path')

function deleteDirectory(dirPath){
    return new Promise((resolve,reject)=>{
        fs.access(dirPath,err=>{
            if(err)reject(err)
            fs.readdir(dirPath,(err,files)=>{
                if(err)reject(err)
                Promise.all(files.map(file=>{
                    return deleteFile(dirPath,file)
                })).then(()=>{
                    fs.rmdir(dirPath,err=>{
                        if(err)reject(err)
                        resolve()
                    })
                }).catch(reject)
            })
        })
    })
}

function deleteFile(dirPath,file){
    return new Promise((resolve,reject)=>{
        let filePath = path.join(dirPath,file)
        fs.stat(filePath,(err,stats)=>{
            if(err)reject(err)
            if(stats.isFile()){
                fs.unlink(filePath,err=>{
                    if(err)reject(err)
                    resolve()
                })
            }else{
                //返回deleteDirectory在all中遞歸調用
                resolve(deleteDirectory(filePath))
            }
        })
    })
}
複製代碼
相關文章
相關標籤/搜索