util.parseArgs([config])
config<Object> 用于提供解析参数并配置解析器。config支持以下属性:args<string[]> 参数字符串数组。默认值: 移除execPath和filename后的process.argv。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' } []