You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Bun检查文件夹是否已存在?

如何用Bun检查文件夹是否存在

你尝试的Bun.file().exists()方法仅适用于文件,对文件夹无效,这就是为什么返回false。以下是几种可行的方案:

方案1:使用Bun原生API Bun.stat()

通过获取路径的状态信息,判断是否为目录:

const targetPath = "folderName";

try {
  const stats = await Bun.stat(targetPath);
  if (stats.isDirectory()) {
    console.log("目标文件夹存在");
  } else {
    console.log("路径存在,但不是文件夹");
  }
} catch {
  console.log("目标文件夹不存在");
}

如果需要封装成复用函数:

async function folderExists(path) {
  try {
    const stats = await Bun.stat(path);
    return stats.isDirectory();
  } catch {
    return false;
  }
}

// 使用示例
const exists = await folderExists("folderName");
console.log(exists); // 存在返回true,否则false

方案2:兼容Node.js的fs模块

Bun完全支持Node.js的文件系统API,你也可以用fs.stat()实现相同功能:

import fs from "fs/promises";

async function folderExists(path) {
  try {
    const stats = await fs.stat(path);
    return stats.isDirectory();
  } catch {
    return false;
  }
}

内容的提问来源于stack exchange,提问作者Little Helper

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 16:27:23