解析命令行参数
参数向量 是运行程序时传递给程序的参数列表。它可以通过 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" ]