How to Find Files with Bun.Glob in Bun
Bun includes Bun.Glob, which finds files using patterns such as **/*.ts. You can use it in build and test scripts without installing any package, for example to collect every .ts file under src or to list only the test files.
Below, I show what ends up in the results and what does not when you search with scan(), how to exclude node_modules and test files, and how match() decides whether a path matches, all with the output from my verification environment. In the second half, I measure how long it takes to search a folder with 55,000 files, and compare how much narrowing the search scope changes the time.
The verification environment was Ubuntu 24.04 (x86_64, 4 CPUs, ext4) with Bun 1.4.4. I wrote the code in TypeScript and ran it with bun filename.ts. The timings were measured on a disposable verification VM, and even with the same method they varied a lot from run to run (by up to about 4x). I did not test Windows, macOS, or other Bun versions. For the official documentation, I checked the documentation files at the release tag bun-v1.4.4 on GitHub, and the links point there.
The folder used for testing
I created a small project like the following for testing. .cache is a folder whose name starts with ., linked-src is a symbolic link pointing to src, and broken-link is a broken symbolic link pointing to a folder that does not exist.
demo
├── .cache/tmp.ts
├── .env
├── app/(marketing)/page.tsx
├── broken-link -> missing-dir
├── docs/README.md
├── index.ts
├── linked-src -> src
├── node_modules/some-lib/index.ts
├── node_modules/some-lib/dist/index.d.ts
├── src/main.ts
├── src/components/Button.tsx
├── src/components/Button.test.tsx
├── src/utils/format.ts
├── src/utils/format.test.ts
├── src/utils/legacy.js
└── tests/e2e.test.ts
Finding .ts files with scan()
Create a Glob with new Glob(pattern), pass the folder to start searching from to scan(), and matching file paths are returned one at a time. scan() is an asynchronous iterator that you loop over with for await. If you want synchronous results, use scanSync() (official documentation on using Glob).
// Find .ts files inside the demo folder
import { Glob } from "bun";
const glob = new Glob("**/*.ts");
for await (const file of glob.scan("demo")) {
console.log(file);
}
$ bun basic.ts
index.ts
node_modules/some-lib/index.ts
node_modules/some-lib/dist/index.d.ts
tests/e2e.test.ts
src/main.ts
src/utils/format.ts
src/utils/format.test.ts
From the results, I found three things:
- Paths are returned relative to the folder passed to
scan() - If you specify nothing, node_modules is also searched
- The order is not alphabetical. If you need a specific order, sort the results after receiving them
*.ts also matches files ending in .d.ts. If you want to exclude type definition files, you can filter the results with match(), as explained later.
If you want all the results in an array, you can write Array.fromAsync(glob.scan(...)) or Array.from(glob.scanSync(...)).
Results that change with scan() options
Instead of a folder name, scan() accepts an options object. Six options are available: cwd, dot, absolute, followSymlinks, throwErrorOnBrokenSymlink, and onlyFiles (type definition of GlobScanOptions). Here are the results of trying each one on demo.
| Option | Default | Result in testing |
|---|---|---|
cwd |
The process's current directory (process.cwd()) |
With "demo/src/components" and *.{ts,tsx}, two results: Button.test.tsx and Button.tsx |
dot |
false |
With true, .cache/tmp.ts was added, changing 7 results to 8 |
absolute |
false |
With true, absolute paths such as /path/to/demo/index.ts were returned (I replaced the path) |
onlyFiles |
true |
With false and the pattern src/*, the folders src/components and src/utils were also returned |
followSymlinks |
false |
With true, the 3 files inside linked-src/ were added to the results of **/*.ts, making 10 |
throwErrorOnBrokenSymlink |
false |
With followSymlinks: true and **/*, the search stopped with an ENOENT error |
Because dot defaults to false, the contents of folders starting with ., such as .cache or .github, are not searched unless you specify otherwise.
followSymlinks behaved in a way that is easy to miss. Even with false, if you write a symbolic link's name in the pattern, such as linked-src/**/*.ts, the 3 files inside it are returned. In the patterns I tried, the only time false did not enter a symbolic link was when the link appeared partway through a path that ** was traversing.
For throwErrorOnBrokenSymlink, when I used onlyFiles: false with * to search only the top level of demo, setting it to true did not cause an error, and broken-link was included in the results. The error occurred when I searched **/* with followSymlinks: true. In the following code, false returned 18 results without broken-link, while true stopped with ENOENT.
// Broken symbolic link: when using ** with followSymlinks: true
import { Glob } from "bun";
const glob = new Glob("**/*");
for (const throwErrorOnBrokenSymlink of [false, true]) {
try {
const r = await Array.fromAsync(glob.scan({ cwd: "demo", followSymlinks: true, throwErrorOnBrokenSymlink }));
console.log(throwErrorOnBrokenSymlink, r.length, "件", r.includes("broken-link"));
} catch (e) {
console.log(throwErrorOnBrokenSymlink, "error:", (e as Error).message, (e as any).code);
}
}
$ bun broken2.ts
false 18 件 false
true error: ENOENT: no such file or directory, open 'broken-link' ENOENT
Excluding node_modules and test files
The scan() method of Bun.Glob has no option for passing exclude patterns. So you create a separate Glob for the patterns you want to exclude, use match() to test each result, and remove the matches from the results.
// Exclude node_modules and test files
import { Glob } from "bun";
const target = new Glob("**/*.{ts,tsx}");
const ignore = [new Glob("node_modules/**"), new Glob("**/*.test.*")];
const files: string[] = [];
for await (const file of target.scan("demo")) {
if (ignore.some((g) => g.match(file))) continue;
files.push(file);
}
console.log(files.sort());
$ bun exclude.ts
[ "app/(marketing)/page.tsx", "index.ts", "src/components/Button.tsx", "src/main.ts", "src/utils/format.ts" ]
Parentheses such as those in app/(marketing) that are not preceded by a symbol like ! or @ are treated as part of the folder name (official documentation on extended patterns).
I also tried excluding within a single pattern. !(*.test) means "anything that does not match *.test." Searching with src/**/!(*.test).{ts,tsx} returned 3 results with the test files excluded. Below are the code and output for this, shown alongside the version that puts ! at the start of the pattern.
const ext = await Array.fromAsync(new Glob("src/**/!(*.test).{ts,tsx}").scan("demo"));
console.log("!(*.test):", ext.sort());
const neg = await Array.fromAsync(new Glob("!**/*.test.ts").scan("demo"));
console.log("先頭の ! :", neg.length, "件", neg.sort().slice(0, 5));
!(*.test): [ "src/components/Button.tsx", "src/main.ts", "src/utils/format.ts" ]
先頭の ! : 0 件 []
On the other hand, !**/*.test.ts, with ! at the start of the pattern, returned no results from scan(). The official documentation includes an example in match() where a leading ! inverts the result (official documentation on the leading !). In my verification environment, I could not collect files with scan() using this form.
The node:fs glob supports exclude
Bun also provides Node.js's fs.glob(), fs.globSync(), and fs.promises.glob(). These accept an array of patterns and an exclude option (official documentation on Node.js fs.glob() compatibility). With the same conditions, it returned the same 5 results as excluding with Bun.Glob and match().
// Exclude with the exclude option of node:fs glob
import { promises } from "node:fs";
const files = await Array.fromAsync(
promises.glob(["**/*.ts", "**/*.tsx"], {
cwd: "demo",
exclude: ["node_modules/**", "**/*.test.*"],
}),
);
console.log(files.sort());
$ bun fsglob.ts
[ "app/(marketing)/page.tsx", "index.ts", "src/components/Button.tsx", "src/main.ts", "src/utils/format.ts" ]
Checking paths with match()
match() does not search for files. It returns true or false depending on whether the string you pass matches the pattern. It is useful when you already have a list of files or when you want to sort changed file paths into groups. The pattern syntax is listed in the official documentation on patterns.
$ bun match.ts
*.ts index.ts=true src/index.ts=false
**/*.ts index.ts=true src/index.ts=true src/index.js=false
src/**/*.test.{ts,tsx} src/a.test.ts=true src/ui/b.test.tsx=true tests/c.test.ts=false
v{1..3}.ts v1.ts=true v3.ts=true v4.ts=false
!(*.test).ts index.ts=true index.test.ts=false
*.ts ./index.ts=false .env.ts=true
src/*.ts src\index.ts=false
*.TS index.ts=false
* does not cross /, so *.ts does not match src/index.ts. To go into subfolders, add **/.
The last three lines contain four examples where results were not what you might expect. In the order they appear:
- A string starting with
./, such as./index.ts, did not match*.ts. Paths returned byscan()do not start with./, so this is not a problem when you pass results fromscan(). match()has nodotoption, so*.tsmatched.env.ts. This differs fromscan(), which by default does not return names starting with..- On Linux,
src\index.ts, which uses\as a separator, did not matchsrc/*.ts. - Matching is case-sensitive, so
*.TSdid not matchindex.ts.
How search time depends on how you narrow the pattern
I measured the time to search for .ts files in a folder containing 5,000 empty files in src and 50,000 in node_modules, for a total of 55,000. There are 1,000 .ts files in src and 10,000 in node_modules. Each run measured 5 times, and I repeated the whole run 3 times.

| Method | Results | Median | Min–max |
|---|---|---|---|
scan() with **/*.ts |
11,000 | 22.8 ms | 18.5–31.4 ms |
scanSync() with **/*.ts |
11,000 | 21.9 ms | 18.6–35.3 ms |
scanSync() with **/*.ts, excluding node_modules with match() on results |
1,000 | 22.3 ms | 16.1–31.5 ms |
scanSync() with src/**/*.ts |
1,000 | 1.4 ms | 1.1–2.4 ms |
node:fs globSync() with **/*.ts, excluding node_modules with exclude |
1,000 | 15.7 ms | 9.3–39.4 ms |
node:fs globSync() with **/*.ts, no exclude |
11,000 | 117.7 ms | 92.3–188.7 ms |
The difference between scan() and scanSync() was within the run-to-run variation.
Even when I excluded node_modules with match() on the results, the time was almost the same as without excluding. match() removes items from results after the search is finished, so only the number of results decreased.
To shorten search time, write the pattern to start with the folder name, such as src/**/*.ts, so the search scope itself is narrowed. In this measurement, that was about 16 times faster than searching with **/*.ts and then excluding (22.3 ms vs. 1.4 ms).
The code used for measurement is below.
// Measure file search time (5 runs each, in milliseconds)
import { Glob } from "bun";
import { globSync } from "node:fs";
const cwd = "bench";
const nm = new Glob("node_modules/**");
const cases: [string, () => Promise<number> | number][] = [
["Glob.scan **/*.ts(node_modules も含む)", async () => (await Array.fromAsync(new Glob("**/*.ts").scan(cwd))).length],
["Glob.scanSync **/*.ts(node_modules も含む)", () => Array.from(new Glob("**/*.ts").scanSync(cwd)).length],
["Glob.scanSync **/*.ts から match() で node_modules を除く", () => Array.from(new Glob("**/*.ts").scanSync(cwd)).filter((f) => !nm.match(f)).length],
["Glob.scanSync src/**/*.ts(探す範囲を src に絞る)", () => Array.from(new Glob("src/**/*.ts").scanSync(cwd)).length],
["node:fs globSync **/*.ts(exclude で node_modules を除く)", () => globSync("**/*.ts", { cwd, exclude: ["node_modules/**"] }).length],
["node:fs globSync **/*.ts(exclude なし)", () => globSync("**/*.ts", { cwd }).length],
];
for (const [label, fn] of cases) {
const times: string[] = [];
let n = 0;
for (let i = 0; i < 5; i++) {
const t = performance.now();
n = await fn();
times.push((performance.now() - t).toFixed(1));
}
console.log(`${label}: ${n}件 ${times.join(" / ")} ms`);
}





