node递归删除文件夹再创建会报错问题解决
2022-05-18 本文已影响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