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 by www.bunjs.com.cn 編集