util.parseArgs([config])


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