> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/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/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
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/bun-zhcndoc/cnUTwgMuf4cCrwC-/icons/typescript.svg?fit=max&auto=format&n=cnUTwgMuf4cCrwC-&q=85&s=e7767043c9e885c34f2d6c8fe2a95217" theme={"theme":{"light":"github-light","dark":"dracula"}}
try {
  await rm("path/to/directory", { recursive: true });
} catch (error) {
  if (error.code === "ENOENT") {
    console.log("目录不存在");
  } else {
    throw error;
  }
}
```

***

更多文件系统操作，请参见 [文档 > API > 文件系统](/runtime/file-io)。
