Skip to content

参数向量 是程序运行时传递给程序的参数列表。它可通过 Bun.argv 获取。

ts
console.log(Bun.argv);

使用参数运行此文件会产生以下结果:

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

要将 argv 解析为更有用的格式,util.parseArgs 会很有用。

示例:

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);

然后输出

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

Bun学习网由www.bunjs.com.cn整理维护