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整理維護