Bun

指南進程

使用 Bun 剖析命令列引數

引數向量是程式執行時傳遞給程式的引數列表。它以 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 會很有幫助。

範例

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" ]