Skip to content

快速開始

掃描目錄查找匹配 *.ts 的文件

ts
import { Glob } from "bun";

const glob = new Glob("**/*.ts");

// 遞歸掃描當前工作目錄及其每個子目錄
for await (const file of glob.scan(".")) {
  console.log(file); // => "index.ts"
}

將字符串與通配符模式匹配

ts
import { Glob } from "bun";

const glob = new Glob("*.ts");

glob.match("index.ts"); // => true
glob.match("index.js"); // => false

Glob 是一個實現以下接口的類:

ts
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;
}

支持的通配符模式

Bun 支持以下通配符模式:

? - 匹配任意單個字符

ts
const glob = new Glob("???.ts");
glob.match("foo.ts"); // => true
glob.match("foobar.ts"); // => false

* - 匹配零個或多個字符,路徑分隔符(/\)除外

ts
const glob = new Glob("*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => false

** - 匹配任意數量的字符,包括 /

ts
const glob = new Glob("**/*.ts");
glob.match("index.ts"); // => true
glob.match("src/index.ts"); // => true
glob.match("src/index.js"); // => false

[ab] - 匹配括號中包含的字符之一,以及字符范圍

ts
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]

ts
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} - 匹配任何給定的模式

ts
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 層),並包含上面的任何通配符。

! - 在模式開頭否定結果

ts
const glob = new Glob("!index.ts");
glob.match("index.ts"); // => false
glob.match("foo.ts"); // => true

\ - 轉義上面的任何特殊字符

ts
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() 函數,並帶有額外功能:

ts
import { glob, globSync, promises } from "node:fs";

// 模式數組
const files = await promises.glob(["**/*.ts", "**/*.js"]);

// 排除模式
const filtered = await promises.glob("**/*", {
  exclude: ["node_modules/**", "*.test.*"],
});

所有三個函數(fs.glob()fs.globSync()fs.promises.glob())都支持:

  • 模式數組作為第一個參數
  • exclude 選項用於過濾結果

Bun學習網由www.bunjs.com.cn整理維護