编辑 1:嘿@Harald,您应该使用 @ziishaned 在上面发布的 del 库。因为它更加干净和可扩展。并使用我的答案来了解它是如何工作的 :)
编辑:2(2021 年 12 月 26 日): 我不知道有一个名为 fs.rm 的 fs 方法,您只需一行代码即可使用它来完成任务.
fs.rm(path_to_delete, { recursive: true }, callback)
// or use the synchronous version
fs.rmSync(path_to_delete, { recursive: true })
上面的代码类似于linux shell命令:rm -r path_to_delete。
我们使用fs.unlink 和fs.rmdir 分别删除文件和空目录。要检查路径是否代表目录,我们可以使用fs.stat()。
所以我们要列出你test目录下的所有内容,并一一删除。
顺便说一句,我将使用上述fs 方法的同步 版本(例如,fs.readdirSync 而不是fs.readdir)来简化我的代码。但是,如果您正在编写一个生产应用程序,那么您应该使用所有 fs 方法的 异步 版本。我留给你阅读这里的文档Node.js v14.18.1 File System documentation。
const fs = require("fs");
const path = require("path");
const DIR_TO_CLEAR = "./trash";
emptyDir(DIR_TO_CLEAR);
function emptyDir(dirPath) {
const dirContents = fs.readdirSync(dirPath); // List dir content
for (const fileOrDirPath of dirContents) {
try {
// Get Full path
const fullPath = path.join(dirPath, fileOrDirPath);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
// It's a sub directory
if (fs.readdirSync(fullPath).length) emptyDir(fullPath);
// If the dir is not empty then remove it's contents too(recursively)
fs.rmdirSync(fullPath);
} else fs.unlinkSync(fullPath); // It's a file
} catch (ex) {
console.error(ex.message);
}
}
}
如果你不明白上面代码中的任何内容,请随时问我:)