Bun

指南进程

使用 Bun 解析命令行参数

参数向量 (argument vector) 是程序运行时传递给程序的参数列表。它可以从 Bun.argv 获取。

cli.ts
console.log(Bun.argv);

运行此文件并带参数将产生以下结果

bun run cli.ts --flag1 --flag2 value
[ '/path/to/bun', '/path/to/cli.ts', '--flag1', '--flag2', 'value' ]

为了将 argv 解析成更有用的格式,util.parseArgs 会很有帮助。

Example

cli.ts
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);

然后它会输出

bun run cli.ts --flag1 --flag2 value
{
  flag1: true,
  flag2: "value",
}
[ "/path/to/bun", "/path/to/cli.ts" ]