要递归删除目录及其所有内容,请使用 `node:fs/promises` 中的 `rm`。这类似于在 JavaScript 中运行 `rm -rf`。
import { rm } from "node:fs/promises";
// Delete a directory and all its contents
await rm("path/to/directory", { recursive: true, force: true });
这些选项配置删除行为
recursive: true- 删除子目录及其内容force: true- 如果目录不存在,不抛出错误
您也可以在不使用 force 的情况下使用它,以确保目录存在
try {
await rm("path/to/directory", { recursive: true });
} catch (error) {
if (error.code === "ENOENT") {
console.log("Directory doesn't exist");
} else {
throw error;
}
}
有关更多文件系统操作,请参阅文档 > API > 文件系统。