如何使用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
相关产品推荐
相关产品推荐

