node fs 文件/目录 删除

删除文件如下:

过程:先判断文件路径是否存在、读取该文件下所有文件、循环该文件,判断是否是文件夹还是文件、

移除文件夹使用fs.rmdirSync("路径")

移除文件使用fs.unlinkSync("路径",function(){err})

if (fs.existsSync(pathImg)) {
    files = fs.readdirSync(pathImg);
    files.forEach(function (file, index) {
        var curPath = pathImg + "/" + file;
        if (fs.statSync(curPath).isDirectory()) { // recurse
            fs.rmdirSync(pathImg);
            console.log("文件夹");
        } else { // delete file
            console.log("删除文件",file);
            fs.unlinkSync(curPath,function (err) {
                if (err) throw err;
            });
        }
    });
    // fs.rmdirSync(pathImg);
}



原文地址:https://www.cnblogs.com/jintaostudy/p/6710063.html