美文网首页
node递归删除文件夹再创建会报错问题解决

node递归删除文件夹再创建会报错问题解决

作者: 姜治宇 | 来源:发表于2022-05-18 14:40 被阅读0次

递归删除文件夹:

const path = require('path');
const fs = require('fs');
const filepath = path.resolve('D:', 'test');

createFolder(filepath);

function deleteFolder(filepath) {
    fs.readdirSync(filepath).forEach(file => {
        let curPath = path.resolve(filepath, file);
        if (fs.statSync(curPath).isDirectory()) { //判断是文件夹,走递归

            deleteFolder(curPath);

        } else {
            fs.unlinkSync(curPath);//普通文件,删除
        }

    });

    fs.rmdirSync(filepath);//删除顶级目录及下面的空文件夹

}

function createFolder(dir) {

    if (fs.existsSync(dir)) {

        deleteFolder(dir);
    }

    fs.mkdirSync(dir);

}

windows下执行可能会抛这样的异常:


1.png

这是因为windows在文件被删除,然后进行恢复时会锁定目录,导致再次创建失败,并不是程序本身的问题。

Note: When a file being watched by fs.watchFile() disappears and reappears, then the previousStat reported in the second callback event (the file's reappearance) will be the same as the previousStat of the first callback event (its disappearance).

This happens when:

the file is deleted, followed by a restore
the file is renamed twice - the second time back to its original name

相关文章

网友评论

      本文标题:node递归删除文件夹再创建会报错问题解决

      本文链接:https://www.haomeiwen.com/subject/xqlaurtx.html