> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 删除目录

要递归删除目录及其所有内容，请使用 `node:fs/promises` 中的 `rm`。这类似于在 JavaScript 中运行 `rm -rf`。

```ts delete-directory.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { rm } from "node:fs/promises";

// 删除目录及其所有内容
await rm("path/to/directory", { recursive: true, force: true });
```

***

这些选项配置了删除行为：

* `recursive: true` - 删除子目录及其内容
* `force: true` - 如果目录不存在则不抛出错误

省略 `force` 以在目录不存在时获取错误：

```ts delete-directory.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
try {
  await rm("path/to/directory", { recursive: true });
} catch (error) {
  if (error.code === "ENOENT") {
    console.log("目录不存在");
  } else {
    throw error;
  }
}
```

***

参见 [文件 I/O](/runtime/file-io) 了解更多文件系统操作。
