NodeJs递归删除非空文件夹

此篇博文由于第一次使用fs.unlink()删除文件夹时报“Error: EPERM: operation not permitted, unlink”错误而写,这是因为fs.unlink()只能删除文件。

fs.rmdir()或fs.rmdirSync()用户删除空文件夹, fs.unlink()或fs.unlinkSync()用于删除文件,因此删除非空文件夹需要使用递归方式。

function deleteFolderRecursive(path) {
    if( fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file) {
            var curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};
原文地址:https://www.cnblogs.com/eczhou/p/7845542.html