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.
快速开始
扫描目录中匹配 *.ts 的文件:
import { Glob } from "bun";
const glob = new Glob("**/*.ts");
// 递归扫描当前工作目录及其所有子目录
for await (const file of glob.scan(".")) {
console.log(file); // => "index.ts"
}
根据 glob 模式匹配字符串:
import { Glob } from "bun";
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("index.js"); // => false
Glob 是一个实现以下接口的类:
class Glob {
scan(root: string | ScanOptions): AsyncIterable<string>;
scanSync(root: string | ScanOptions): Iterable<string>;
match(path: string): boolean;
}
interface ScanOptions {
/**
* 匹配起始的根目录。默认为 `process.cwd()`
*/
cwd?: string;
/**
* 允许模式匹配以点 (`.`) 开头的条目。
*
* @default false
*/
dot?: boolean;
/**
* 返回条目的绝对路径。
*
* @default false
*/
absolute?: boolean;
/**
* 指示是否遍历符号链接目录的子孙目录。
*
* @default false
*/
followSymlinks?: boolean;
/**
* 当符号链接损坏时抛出错误。
*
* @default false
*/
throwErrorOnBrokenSymlink?: boolean;
/**
* 只返回文件。
*
* @default true
*/
onlyFiles?: boolean;
}
支持的 Glob 模式
Bun 支持以下 glob 模式:
? - 匹配任意单个字符
const glob = new Glob("???.ts");
glob.match("foo.ts"); // => true
glob.match("foobar.ts"); // => false
* - 匹配零个或多个字符,但不包括路径分隔符(/ 或 \)
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => false
** - 匹配任意数量的字符,包括路径分隔符 /
const glob = new Glob("**/*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => true
glob.match("src/index.js"); // => false
[ab] - 匹配括号中包含的任意字符,以及字符范围
const glob = new Glob("ba[rz].ts");
glob.match("bar.ts"); // => true
glob.match("baz.ts"); // => true
glob.match("bat.ts"); // => false
你可以使用字符范围(例如 [0-9]、[a-z])以及取反操作符 ^ 或 ! 来匹配不包含括号内字符的任意字符(例如 [^ab]、[!a-z])
const glob = new Glob("ba[a-z][0-9][^4-9].ts");
glob.match("bar01.ts"); // => true
glob.match("baz83.ts"); // => true
glob.match("bat22.ts"); // => true
glob.match("bat24.ts"); // => false
glob.match("ba0a8.ts"); // => false
{a,b,c} - 匹配任意给定的模式
const glob = new Glob("{a,b,c}.ts");
glob.match("a.ts"); // => true
glob.match("b.ts"); // => true
glob.match("c.ts"); // => true
glob.match("d.ts"); // => false
这些匹配模式可以深度嵌套(最多 10 层),并且包含以上任意通配符。
! - 在模式开头表示取反
const glob = new Glob("!index.ts");
glob.match("index.ts"); // => false
glob.match("foo.ts"); // => true
\ - 转义上述任意特殊字符
const glob = new Glob("\\!index.ts");
glob.match("!index.ts"); // => true
glob.match("index.ts"); // => false
Node.js 的 fs.glob() 兼容性
Bun 同时实现了 Node.js 的 fs.glob() 函数,并增加了附加功能:
import { glob, globSync, promises } from "node:fs";
// 模式数组
const files = await promises.glob(["**/*.ts", "**/*.js"]);
// 排除模式
const filtered = await promises.glob("**/*", {
exclude: ["node_modules/**", "*.test.*"],
});
这三个函数均支持:
- 作为第一个参数的模式数组
- 用于过滤结果的
exclude 选项