Bun 包含一個快速原生檔案 glob 實作。
快速入門
掃描目錄中符合 *.ts
的檔案:
import { Glob } from "bun";
const glob = new Glob("**/*.ts");
// Scans the current working directory and each of its sub-directories recursively
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 {
/**
* The root directory to start matching from. Defaults to `process.cwd()`
*/
cwd?: string;
/**
* Allow patterns to match entries that begin with a period (`.`).
*
* @default false
*/
dot?: boolean;
/**
* Return the absolute path for entries.
*
* @default false
*/
absolute?: boolean;
/**
* Indicates whether to traverse descendants of symbolic link directories.
*
* @default false
*/
followSymlinks?: boolean;
/**
* Throw an error when symbolic link is broken
*
* @default false
*/
throwErrorOnBrokenSymlink?: boolean;
/**
* Return only files.
*
* @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