util.parseArgs([config])


版本历史
版本变更
v22.4.0, v20.16.0

add support for allowing negative options in input config.

v20.0.0

The API is no longer experimental.

v18.11.0, v16.19.0

Add support for default values in input config.

v18.7.0, v16.17.0

add support for returning detailed parse information using tokens in input config and returned properties.

v18.3.0, v16.17.0

新增于: v18.3.0, v16.17.0

  • config <Object> 用于提供解析参数以及配置解析器。config 支持以下属性:
    • args <string[]> 参数字符串数组。默认值: process.argv,移除了 execPathfilename
    • options <Object> 用于描述解析器已知的参数。options 的键是选项的长名称,值是一个 <Object>,接受以下属性:
      • type <string> 参数类型,必须是 booleanstring
      • multiple <boolean> 是否可以多次提供此选项。如果为 true,所有值将被收集到一个数组中。如果为 false,该选项的值以最后一个为准。默认值: false
      • short <string> 该选项的单字符别名。
      • default <string> | <boolean> | <string[]> | <boolean[]> 如果在要解析的参数中未出现该选项,则为该选项分配的值。该值必须与 type 属性指定的类型匹配。如果 multipletrue,它必须是一个数组。当选项出现在要解析的参数中时,即使提供的值为假值,也不会应用默认值。
    • strict <boolean> 当遇到未知参数,或传递的参数与在 options 中配置的 type 不匹配时,是否应该抛出错误。默认值: true
    • allowPositionals <boolean> 该命令是否接受位置参数。默认值: 如果 stricttrue,则为 false,否则为 true
    • allowNegative <boolean> 如果 true,可以通过在选项名称前加上 --no- 来明确设置布尔选项为 false默认值: false
    • tokens <boolean> 返回解析后的标记。这对于扩展内置行为非常有用,从添加额外的检查到以不同方式重新处理标记。默认值: false
  • 返回:<Object> 解析的命令行参数:

提供比直接使用 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' } []

AltStyle によって変換されたページ (->オリジナル) /