> ## Documentation Index
> Fetch the complete documentation index at: https://bun.ll1025.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 文件系统路由器

> Bun 提供了一个快速 API，用于根据文件系统路径解析路由

此 API 主要面向库作者。它只支持 Next.js 风格的文件系统路由。

## Next.js 风格

`FileSystemRouter` 类针对 `pages` 目录解析路由。（不支持 Next.js 13 的 `app` 目录。）考虑以下 `pages` 目录：

```txt theme={null}
pages
├── index.tsx
├── settings.tsx
├── blog
│   ├── [slug].tsx
│   └── index.tsx
└── [[...catchall]].tsx
```

针对此目录解析路由：

```ts router.ts theme={null}
const router = new Bun.FileSystemRouter({
  style: "nextjs",
  dir: "./pages",
  origin: "https://mydomain.com",
  assetPrefix: "_next/static/"
});

router.match("/");

// =>
{
  filePath: "/path/to/pages/index.tsx",
  kind: "exact",
  name: "/",
  pathname: "/",
  src: "https://mydomain.com/_next/static/index.tsx"
}
```

查询参数会被解析并返回到 `query` 属性中。

```ts theme={null}
router.match("/settings?foo=bar");

// =>
{
  filePath: "/Users/colinmcd94/Documents/bun/fun/pages/settings.tsx",
  kind: "exact",
  name: "/settings",
  pathname: "/settings?foo=bar",
  src: "https://mydomain.com/_next/static/settings.tsx",
  query: {
    foo: "bar"
  }
}
```

路由器会解析 URL 参数并将其返回到 `params` 属性中：

```ts theme={null}
router.match("/blog/my-cool-post");

// =>
{
  filePath: "/Users/colinmcd94/Documents/bun/fun/pages/blog/[slug].tsx",
  kind: "dynamic",
  name: "/blog/[slug]",
  pathname: "/blog/my-cool-post",
  src: "https://mydomain.com/_next/static/blog/[slug].tsx",
  params: {
    slug: "my-cool-post"
  }
}
```

`.match()` 方法也接受 `Request` 和 `Response` 对象；它们的 `url` 属性用于解析路由。

```ts theme={null}
router.match(new Request("https://example.com/blog/my-cool-post"));
```

路由器在初始化时会读取目录内容。要重新扫描文件，请使用 `.reload()` 方法。

```ts theme={null}
router.reload();
```

## 参考

```ts theme={null}
interface Bun {
  class FileSystemRouter {
    constructor(params: {
      dir: string;
      style: "nextjs";
      origin?: string;
      assetPrefix?: string;
      fileExtensions?: string[];
    });

    reload(): void;

    match(path: string | Request | Response): {
      filePath: string;
      kind: "exact" | "catch-all" | "optional-catch-all" | "dynamic";
      name: string;
      pathname: string;
      src: string;
      params?: Record<string, string>;
      query?: Record<string, string>;
    } | null
  }
}
```
