> ## 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.argv` 获取。

```ts cli.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
console.log(Bun.argv);
```

***

运行此文件并传入参数会得到以下结果：

```sh terminal icon="terminal" theme={null}
bun run cli.ts --flag1 --flag2 value
```

```txt theme={null}
[ "/path/to/bun", "/path/to/cli.ts", "--flag1", "--flag2", "value" ]
```

***

若要将 `argv` 解析为更有用的格式，可使用 `util.parseArgs`。

```ts cli.ts icon="https://mintcdn.com/span-inc/82N53aP7NFbaCVSl/icons/typescript.svg?fit=max&auto=format&n=82N53aP7NFbaCVSl&q=85&s=787d39d6a7d96d7f9540dc74344eba23" theme={null}
import { parseArgs } from "util";

const { values, positionals } = parseArgs({
  args: Bun.argv,
  options: {
    flag1: {
      type: "boolean",
    },
    flag2: {
      type: "string",
    },
  },
  strict: true,
  allowPositionals: true,
});

console.log(values);
console.log(positionals);
```

***

使用相同参数运行 `cli.ts` 会打印解析后的值。

```sh terminal icon="terminal" theme={null}
bun run cli.ts --flag1 --flag2 value
```

```txt theme={null}
[Object: null prototype] {
  flag1: true,
  flag2: "value",
}
[ "/path/to/bun", "/path/to/cli.ts" ]
```
