Bun

指南執行時

使用 Bun 刪除目錄

要遞迴刪除目錄及其所有內容,請使用 `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 > 檔案系統