@pkgjs/parseargs

中文文档
0.11.0发布于 2022/10/10MITCommonJS零依赖近 30 天下载 3.7亿

Polyfill of future proposal for util.parseArgs()

原始使用文档
文档目录12 节
  1. util.parseArgs([config])
  2. parseArgs tokens
  3. Table of Contents
  4. Scope
  5. Version Matchups
  6. 🚀 Getting Started
  7. 🙌 Contributing
  8. 💡 process.mainArgs Proposal
  9. Implementation:
  10. 📃 Examples
  11. F.A.Qs
  12. Links & Resources

parseArgs

Coverage

Polyfill of util.parseArgs()

util.parseArgs([config])

Stability: 1 - Experimental

  • config {Object} Used to provide arguments for parsing and to configure the parser. config supports the following properties:

    • args {string[]} array of argument strings. Default: process.argv with execPath and filename removed.
    • options {Object} Used to describe arguments known to the parser. Keys of options are the long names of options and values are an {Object} accepting the following properties:
      • type {string} Type of argument, which must be either boolean or string.
      • multiple {boolean} Whether this option can be provided multiple times. If true, all values will be collected in an array. If false, values for the option are last-wins. Default: false.
      • short {string} A single character alias for the option.
      • default {string | boolean | string[] | boolean[]} The default option value when it is not set by args. It must be of the same type as the the type property. When multiple is true, it must be an array.
    • strict {boolean} Should an error be thrown when unknown arguments are encountered, or when arguments are passed that do not match the type configured in options. Default: true.
    • allowPositionals {boolean} Whether this command accepts positional arguments. Default: false if strict is true, otherwise true.
    • tokens {boolean} Return the parsed tokens. This is useful for extending the built-in behavior, from adding additional checks through to reprocessing the tokens in different ways. Default: false.
  • Returns: {Object} The parsed command line arguments:

    • values {Object} A mapping of parsed option names with their {string} or {boolean} values.
    • positionals {string[]} Positional arguments.
    • tokens {Object[] | undefined} See parseArgs tokens section. Only returned if config includes tokens: true.

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' } []

util.parseArgs is experimental and behavior may change. Join the conversation in pkgjs/parseargs to contribute to the design.

parseArgs tokens

Detailed parse information is available for adding custom behaviours by specifying tokens: true in the configuration. The returned tokens have properties describing:

  • all tokens
    • kind {string} One of 'option', 'positional', or 'option-terminator'.
    • index {number} Index of element in args containing token. So the source argument for a token is args[token.index].
  • option tokens
    • name {string} Long name of option.
    • rawName {string} How option used in args, like -f of --foo.
    • value {string | undefined} Option value specified in args. Undefined for boolean options.
    • inlineValue {boolean | undefined} Whether option value specified inline, like --foo=bar.
  • positional tokens
    • value {string} The value of the positional argument in args (i.e. args[index]).
  • option-terminator token

The returned tokens are in the order encountered in the input args. Options that appear more than once in args produce a token for each use. Short option groups like -xy expand to a token for each option. So -xxx produces three tokens.

For example to use the returned tokens to add support for a negated option like --no-color, the tokens can be reprocessed to change the value stored for the negated option.

import { parseArgs } from 'node:util';

const options = {
  'color': { type: 'boolean' },
  'no-color': { type: 'boolean' },
  'logfile': { type: 'string' },
  'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });

// Reprocess the option tokens and overwrite the returned values.
tokens
  .filter((token) => token.kind === 'option')
  .forEach((token) => {
    if (token.name.startsWith('no-')) {
      // Store foo:false for --no-foo
      const positiveName = token.name.slice(3);
      values[positiveName] = false;
      delete values[token.name];
    } else {
      // Resave value so last one wins if both --foo and --no-foo.
      values[token.name] = token.value ?? true;
    }
  });

const color = values.color;
const logfile = values.logfile ?? 'default.log';

console.log({ logfile, color });
const { parseArgs } = require('node:util');

const options = {
  'color': { type: 'boolean' },
  'no-color': { type: 'boolean' },
  'logfile': { type: 'string' },
  'no-logfile': { type: 'boolean' },
};
const { values, tokens } = parseArgs({ options, tokens: true });

// Reprocess the option tokens and overwrite the returned values.
tokens
  .filter((token) => token.kind === 'option')
  .forEach((token) => {
    if (token.name.startsWith('no-')) {
      // Store foo:false for --no-foo
      const positiveName = token.name.slice(3);
      values[positiveName] = false;
      delete values[token.name];
    } else {
      // Resave value so last one wins if both --foo and --no-foo.
      values[token.name] = token.value ?? true;
    }
  });

const color = values.color;
const logfile = values.logfile ?? 'default.log';

console.log({ logfile, color });

Example usage showing negated options, and when an option is used multiple ways then last one wins.

$ node negate.js
{ logfile: 'default.log', color: undefined }
$ node negate.js --no-logfile --no-color
{ logfile: false, color: false }
$ node negate.js --logfile=test.log --color
{ logfile: 'test.log', color: true }
$ node negate.js --no-logfile --logfile=test.log --color --no-color
{ logfile: 'test.log', color: false }

Table of Contents


Scope

It is already possible to build great arg parsing modules on top of what Node.js provides; the prickly API is abstracted away by these modules. Thus, process.parseArgs() is not necessarily intended for library authors; it is intended for developers of simple CLI tools, ad-hoc scripts, deployed Node.js applications, and learning materials.

It is exceedingly difficult to provide an API which would both be friendly to these Node.js users while being extensible enough for libraries to build upon. We chose to prioritize these use cases because these are currently not well-served by Node.js' API.


Version Matchups

Node.js@pkgjs/parseArgs
v18.3.0v0.9.1
v16.17.0, v18.7.00.10.0

🚀 Getting Started

  1. Install dependencies.

    npm install
    
  2. Open the index.js file and start editing!

  3. Test your code by calling parseArgs through our test file

    npm test
    

🙌 Contributing

Any person who wants to contribute to the initiative is welcome! Please first read the Contributing Guide

Additionally, reading the Examples w/ Output section of this document will be the best way to familiarize yourself with the target expected behavior for parseArgs() once it is fully implemented.

This package was implemented using tape as its test harness.


💡 process.mainArgs Proposal

Note: This can be moved forward independently of the util.parseArgs() proposal/work.

Implementation:

process.mainArgs = process.argv.slice(process._exec ? 1 : 2)

📃 Examples

const { parseArgs } = require('@pkgjs/parseargs');
const { parseArgs } = require('@pkgjs/parseargs');
// specify the options that may be used
const options = {
  foo: { type: 'string'},
  bar: { type: 'boolean' },
};
const args = ['--foo=a', '--bar'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: 'a', bar: true }
// positionals = []
const { parseArgs } = require('@pkgjs/parseargs');
// type:string & multiple
const options = {
  foo: {
    type: 'string',
    multiple: true,
  },
};
const args = ['--foo=a', '--foo', 'b'];
const { values, positionals } = parseArgs({ args, options });
// values = { foo: [ 'a', 'b' ] }
// positionals = []
const { parseArgs } = require('@pkgjs/parseargs');
// shorts
const options = {
  foo: {
    short: 'f',
    type: 'boolean'
  },
};
const args = ['-f', 'b'];
const { values, positionals } = parseArgs({ args, options, allowPositionals: true });
// values = { foo: true }
// positionals = ['b']
const { parseArgs } = require('@pkgjs/parseargs');
// unconfigured
const options = {};
const args = ['-f', '--foo=a', '--bar', 'b'];
const { values, positionals } = parseArgs({ strict: false, args, options, allowPositionals: true });
// values = { f: true, foo: 'a', bar: true }
// positionals = ['b']

F.A.Qs

  • Is cmd --foo=bar baz the same as cmd baz --foo=bar?
    • yes
  • Does the parser execute a function?
    • no
  • Does the parser execute one of several functions, depending on input?
    • no
  • Can subcommands take options that are distinct from the main command?
    • no
  • Does it output generated help when no options match?
    • no
  • Does it generated short usage? Like: usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]
    • no (no usage/help at all)
  • Does the user provide the long usage text? For each option? For the whole command?
    • no
  • Do subcommands (if implemented) have their own usage output?
    • no
  • Does usage print if the user runs cmd --help?
    • no
  • Does it set process.exitCode?
    • no
  • Does usage print to stderr or stdout?
    • N/A
  • Does it check types? (Say, specify that an option is a boolean, number, etc.)
    • no
  • Can an option have more than one type? (string or false, for example)
    • no
  • Can the user define a type? (Say, type: path to call path.resolve() on the argument.)
    • no
  • Does a --foo=0o22 mean 0, 22, 18, or "0o22"?
    • "0o22"
  • Does it coerce types?
    • no
  • Does --no-foo coerce to --foo=false? For all options? Only boolean options?
    • no, it sets {values:{'no-foo': true}}
  • Is --foo the same as --foo=true? Only for known booleans? Only at the end?
    • no, they are not the same. There is no special handling of true as a value so it is just another string.
  • Does it read environment variables? Ie, is FOO=1 cmd the same as cmd --foo=1?
    • no
  • Do unknown arguments raise an error? Are they parsed? Are they treated as positional arguments?
    • no, they are parsed, not treated as positionals
  • Does -- signal the end of options?
    • yes
  • Is -- included as a positional?
    • no
  • Is program -- foo the same as program foo?
    • yes, both store {positionals:['foo']}
  • Does the API specify whether a -- was present/relevant?
    • no
  • Is -bar the same as --bar?
  • Is ---foo the same as --foo?
    • no
    • the first is a long option named '-foo'
    • the second is a long option named 'foo'
  • Is - a positional? ie, bash some-test.sh | tap -
    • yes

版本与发布记录

@pkgjs/parseargs 共发布 14 个版本,首次发布于 2022/01/23;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.11.0latest2022/10/104 年前
0.10.02022/07/284 年前
0.9.12022/06/214 年前
0.9.02022/05/254 年前
0.8.02022/05/164 年前
0.7.12022/04/164 年前

关于 @pkgjs/parseargs 的常见问题

@pkgjs/parseargs 是什么?

Polyfill of future proposal for util.parseArgs()

如何安装 @pkgjs/parseargs?

在项目目录运行 npm install @pkgjs/parseargs,或使用 pnpm add / yarn add / bun add。

@pkgjs/parseargs 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/pkgjs__parseargs 是否存在。

@pkgjs/parseargs 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@pkgjs/parseargs 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=14。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@pkgjs/parseargs 可以商用吗?

@pkgjs/parseargs 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@pkgjs/parseargs 的下载量有多少?

根据 npm 官方下载统计,@pkgjs/parseargs 在 2026/10/07 – 2026/11/05 这 30 天内被下载 367,059,674 次,日均约 12,235,322 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@pkgjs/parseargs 还在维护吗?

最新版本 0.11.0 发布于 2022/10/10(4 年前);至今共发布 14 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/01/23。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。