命令行参数
在 Github 上编辑
命令行参数通常用于将配置选项传递给程序。
您可以从 `Deno.args` 获取命令行参数列表。
const name = Deno.args[0];
const food = Deno.args[1];
console.log(`Hello ${name}, I like ${food}!`);
通常您希望将命令行参数(如 `--foo=bar`)解析为结构化数据。这可以使用 `std/cli` 完成。
import { parseArgs } from "jsr:@std/cli/parse-args";
`parseArgs` 函数接受参数列表和选项列表。在这些选项中,您可以指定接受的参数类型以及可能的默认值。返回一个包含解析后的参数的对象。注意:此函数基于 [`minimist`](https://github.com/minimistjs/minimist),与 `node:util` 中的 `parseArgs()` 函数不兼容。
const flags = parseArgs(Deno.args, {
boolean: ["help", "color"],
string: ["version"],
default: { color: true },
negatable: ["color"],
});
console.log("Wants help?", flags.help);
console.log("Version:", flags.version);
console.log("Wants color?:", flags.color);
返回对象的 `_` 字段包含所有未被识别为标志的参数。
console.log("Other:", flags._);
使用 Deno CLI 在本地运行此示例
deno run https://docs.deno.org.cn/examples/scripts/command_line_arguments.ts Deno Sushi --help --version=1.0.0 --no-color