解析命令列引數
引數向量 是執行程式時傳遞給程式的引數列表。它可以通過 Bun.argv 獲取。
console.log(Bun.argv);
執行該檔案並傳入引數輸出如下:
terminal
bun run cli.ts --flag1 --flag2 value
Text
[ "/path/to/bun", "/path/to/cli.ts", "--flag1", "--flag2", "value" ]
要將 argv 解析為更實用的格式,請使用 util.parseArgs。
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);
使用相同的引數執行 cli.ts,會輸出解析後的值。
terminal
bun run cli.ts --flag1 --flag2 value
Text
[Object: null prototype] {
flag1: true,
flag2: "value",
}
[ "/path/to/bun", "/path/to/cli.ts" ]