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

能否使用Bun列出目录中的文件?

如何用Bun列出目录中的文件

当然可以,Bun提供了两种可靠的方式来列出目录中的文件:

1. 使用Node.js兼容的fs模块

Bun完全兼容Node.js核心API,所以你可以直接用熟悉的fs/promises模块实现:

import { readdir } from "fs/promises";

async function listFiles(dirPath = "./") {
  try {
    // withFileTypes: true 可区分文件/目录
    const entries = await readdir(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      console.log(entry.isDirectory() ? `[DIR] ${entry.name}` : entry.name);
    }
  } catch (err) {
    console.error("读取目录出错:", err);
  }
}

listFiles();

2. 使用Bun原生Bun.readdir()方法

Bun提供了原生的文件系统API,性能比Node.js的fs更优,用法类似:

async function listFilesWithBun(dirPath = "./") {
  try {
    const entries = await Bun.readdir(dirPath, { withFileTypes: true });
    for (const entry of entries) {
      console.log(entry.isDirectory() ? `[DIR] ${entry.name}` : entry.name);
    }
  } catch (err) {
    console.error("读取目录出错:", err);
  }
}

listFilesWithBun();

小提示

  • 若只需要文件名(无需区分类型),可以移除withFileTypes: true选项,直接得到字符串数组。
  • 你之前查阅的util指南未覆盖该功能,是因为文件系统操作属于Bun的核心IO能力,相关细节在Bun的文件系统章节中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:48:11