util.parseArgs([config])
config<Object> 用于提供解析参数以及配置解析器。config支持以下属性:args<string[]> 参数字符串数组。默认值:process.argv,移除了execPath和filename。options<Object> 用于描述解析器已知的参数。options的键是选项的长名称,值是一个 <Object>,接受以下属性:type<string> 参数类型,必须是boolean或string。multiple<boolean> 是否可以多次提供此选项。如果为true,所有值将被收集到一个数组中。如果为false,该选项的值以最后一个为准。默认值:false。short<string> 该选项的单字符别名。default<string> | <boolean> | <string[]> | <boolean[]> 如果在要解析的参数中未出现该选项,则为该选项分配的值。该值必须与type属性指定的类型匹配。如果multiple为true,它必须是一个数组。当选项出现在要解析的参数中时,即使提供的值为假值,也不会应用默认值。
strict<boolean> 当遇到未知参数,或传递的参数与在options中配置的type不匹配时,是否应该抛出错误。默认值:true。allowPositionals<boolean> 该命令是否接受位置参数。默认值: 如果strict是true,则为false,否则为true。allowNegative<boolean> 如果true,可以通过在选项名称前加上--no-来明确设置布尔选项为false。默认值:false。tokens<boolean> 返回解析后的标记。这对于扩展内置行为非常有用,从添加额外的检查到以不同方式重新处理标记。默认值:false。
- 返回:<Object> 解析的命令行参数:
values<Object> 已解析选项名称及其 <string> 或 <boolean> 值的映射。positionals<string[]> 位置参数。tokens<Object[]> | <undefined> 请参阅 parseArgs tokens 部分。仅在config包含tokens: true时返回。
提供比直接使用 process.argv 更高级的命令行参数解析 API。它接受一个预期参数的规范,并返回包含解析选项和位置参数的结构化对象。
🌐 Provides a higher level API for command-line argument parsing than interacting
with process.argv directly. Takes a specification for the expected arguments
and returns a structured object with the parsed options and positionals.
import { parseArgs } from 'node:util';
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []const { parseArgs } = require('node:util');
const args = ['-f', '--bar', 'b'];
const options = {
foo: {
type: 'boolean',
short: 'f',
},
bar: {
type: 'string',
},
};
const {
values,
positionals,
} = parseArgs({ args, options });
console.log(values, positionals);
// Prints: [Object: null prototype] { foo: true, bar: 'b' } []