Glob
使用 Bun 的快速本地檔案匹配實現
快速開始
掃描目錄中匹配 *.ts 的檔案:
TypeScript
import { Glob } from "bun";
const glob = new Glob("**/*.ts");
// 遞迴掃描當前工作目錄及其所有子目錄
for await (const file of glob.scan(".")) {
console.log(file); // => "index.ts"
}
根據 glob 模式匹配字串:
TypeScript
import { Glob } from "bun";
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("index.js"); // => false
Glob 類實現了以下介面:
TypeScript
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 模式:
? - 匹配任意單個字元
TypeScript
const glob = new Glob("???.ts");
glob.match("foo.ts"); // => true
glob.match("foobar.ts"); // => false
* - 匹配零個或多個字元,但不包括路徑分隔符(/ 或 \)
TypeScript
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => false
** - 匹配任意數量的字元,包括路徑分隔符 /
TypeScript
const glob = new Glob("**/*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => true
glob.match("src/index.js"); // => false
[ab] - 匹配括號中包含的任意字元,以及字元範圍
TypeScript
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])。
TypeScript
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} - 匹配任意給定的模式
TypeScript
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 層,並且可以包含前面介紹的任意萬用字元。
! - 在模式開頭表示取反
TypeScript
const glob = new Glob("!index.ts");
glob.match("index.ts"); // => false
glob.match("foo.ts"); // => true
\ - 轉義上述任意特殊字元
TypeScript
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() 函式:
TypeScript
import { glob, globSync, promises } from "node:fs";
// Array of patterns
const files = await Array.fromAsync(promises.glob(["**/*.ts", "**/*.js"]));
// Exclude patterns
const filtered = await Array.fromAsync(
promises.glob("**/*", {
exclude: ["node_modules/**", "**/*.test.*"],
}),
);
這三個函式均支援:
- 作為第一個引數的模式陣列
- 用於過濾結果的
exclude選項。