node.js实现删除文件夹

一般的删除文件夹是使用方法fs.rmdir,但是这种方法不能删除里面有内容的文件夹,下面就用代码实现以下可以删除里面有东西的文件夹

const fs=require("fs");
const p=require("path");
let path=p.join(__dirname,"./test2");
deleteFolder(path);
function deleteFolder(path) {
    let files = [];
    if( fs.existsSync(path) ) {
        files = fs.readdirSync(path);
        files.forEach(function(file,index){
            let curPath = path + "/" + file;
            if(fs.statSync(curPath).isDirectory()) {
                deleteFolder(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
}

这种方法的思路就是遍历文件夹,里面的内容如果是文件就直接删掉,如果是文件夹的话,就递归再次执行一次这个函数,参数就变成了这个文件夹,最后在把原本的文件夹删掉就ok了,这种方法最后打印结果也是在控制台打印的。

你可能感兴趣的:(node)