arg

中文文档
5.0.2发布于 2022/06/06MITTypeScriptCommonJS零依赖近 30 天下载 4.1亿

Unopinionated, no-frills CLI argument parser

原始使用文档
文档目录5 节
  1. Installation
  2. Usage
  3. Options
  4. Errors
  5. How do I require an argument with arg ?

Arg

arg is an unopinionated, no-frills CLI argument parser.

Installation

npm install arg

Usage

arg() takes either 1 or 2 arguments:

  1. Command line specification object (see below)
  2. Parse options (Optional, defaults to {permissive: false, argv: process.argv.slice(2), stopAtPositional: false})

It returns an object with any values present on the command-line (missing options are thus missing from the resulting object). Arg performs no validation/requirement checking - we leave that up to the application.

All parameters that aren't consumed by options (commonly referred to as "extra" parameters) are added to result._, which is always an array (even if no extra parameters are passed, in which case an empty array is returned).

const arg = require('arg');

// `options` is an optional parameter
const args = arg(
    spec,
    (options = { permissive: false, argv: process.argv.slice(2) })
);

For example:

$ node ./hello.js --verbose -vvv --port=1234 -n 'My name' foo bar --tag qux --tag=qix -- --foobar
// hello.js
const arg = require('arg');

const args = arg({
    // Types
    '--help': Boolean,
    '--version': Boolean,
    '--verbose': arg.COUNT, // Counts the number of times --verbose is passed
    '--port': Number, // --port <number> or --port=<number>
    '--name': String, // --name <string> or --name=<string>
    '--tag': [String], // --tag <string> or --tag=<string>

    // Aliases
    '-v': '--verbose',
    '-n': '--name', // -n <string>; result is stored in --name
    '--label': '--name' // --label <string> or --label=<string>;
    //     result is stored in --name
});

console.log(args);
/*
{
    _: ["foo", "bar", "--foobar"],
    '--port': 1234,
    '--verbose': 4,
    '--name': "My name",
    '--tag': ["qux", "qix"]
}
*/

The values for each key=>value pair is either a type (function or [function]) or a string (indicating an alias).

  • In the case of a function, the string value of the argument's value is passed to it, and the return value is used as the ultimate value.

  • In the case of an array, the only element must be a type function. Array types indicate that the argument may be passed multiple times, and as such the resulting value in the returned object is an array with all of the values that were passed using the specified flag.

  • In the case of a string, an alias is established. If a flag is passed that matches the key, then the value is substituted in its place.

Type functions are passed three arguments:

  1. The parameter value (always a string)
  2. The parameter name (e.g. --label)
  3. The previous value for the destination (useful for reduce-like operations or for supporting -v multiple times, etc.)

This means the built-in String, Number, and Boolean type constructors "just work" as type functions.

Note that Boolean and [Boolean] have special treatment - an option argument is not consumed or passed, but instead true is returned. These options are called "flags".

For custom handlers that wish to behave as flags, you may pass the function through arg.flag():

const arg = require('arg');

const argv = [
    '--foo',
    'bar',
    '-ff',
    'baz',
    '--foo',
    '--foo',
    'qux',
    '-fff',
    'qix'
];

function myHandler(value, argName, previousValue) {
    /* `value` is always `true` */
    return 'na ' + (previousValue || 'batman!');
}

const args = arg(
    {
        '--foo': arg.flag(myHandler),
        '-f': '--foo'
    },
    {
        argv
    }
);

console.log(args);
/*
{
    _: ['bar', 'baz', 'qux', 'qix'],
    '--foo': 'na na na na na na na na batman!'
}
*/

As well, arg supplies a helper argument handler called arg.COUNT, which equivalent to a [Boolean] argument's .length property - effectively counting the number of times the boolean flag, denoted by the key, is passed on the command line.. For example, this is how you could implement ssh's multiple levels of verbosity (-vvvv being the most verbose).

const arg = require('arg');

const argv = ['-AAAA', '-BBBB'];

const args = arg(
    {
        '-A': arg.COUNT,
        '-B': [Boolean]
    },
    {
        argv
    }
);

console.log(args);
/*
{
    _: [],
    '-A': 4,
    '-B': [true, true, true, true]
}
*/

Options

If a second parameter is specified and is an object, it specifies parsing options to modify the behavior of arg().

argv

If you have already sliced or generated a number of raw arguments to be parsed (as opposed to letting arg slice them from process.argv) you may specify them in the argv option.

For example:

const args = arg(
    {
        '--foo': String
    },
    {
        argv: ['hello', '--foo', 'world']
    }
);

results in:

const args = {
    _: ['hello'],
    '--foo': 'world'
};

permissive

When permissive set to true, arg will push any unknown arguments onto the "extra" argument array (result._) instead of throwing an error about an unknown flag.

For example:

const arg = require('arg');

const argv = [
    '--foo',
    'hello',
    '--qux',
    'qix',
    '--bar',
    '12345',
    'hello again'
];

const args = arg(
    {
        '--foo': String,
        '--bar': Number
    },
    {
        argv,
        permissive: true
    }
);

results in:

const args = {
    _: ['--qux', 'qix', 'hello again'],
    '--foo': 'hello',
    '--bar': 12345
};

stopAtPositional

When stopAtPositional is set to true, arg will halt parsing at the first positional argument.

For example:

const arg = require('arg');

const argv = ['--foo', 'hello', '--bar'];

const args = arg(
    {
        '--foo': Boolean,
        '--bar': Boolean
    },
    {
        argv,
        stopAtPositional: true
    }
);

results in:

const args = {
    _: ['hello', '--bar'],
    '--foo': true
};

Errors

Some errors that arg throws provide a .code property in order to aid in recovering from user error, or to differentiate between user error and developer error (bug).

ARG_UNKNOWN_OPTION

If an unknown option (not defined in the spec object) is passed, an error with code ARG_UNKNOWN_OPTION will be thrown:

// cli.js
try {
    require('arg')({ '--hi': String });
} catch (err) {
    if (err.code === 'ARG_UNKNOWN_OPTION') {
        console.log(err.message);
    } else {
        throw err;
    }
}
node cli.js --extraneous true
Unknown or unexpected option: --extraneous

FAQ

A few questions and answers that have been asked before:

How do I require an argument with arg?

Do the assertion yourself, such as:

const args = arg({ '--name': String });

if (!args['--name']) throw new Error('missing required argument: --name');

License

Released under the MIT License.

版本与发布记录

arg 共发布 14 个版本,首次发布于 2012/06/01;过去 12 个月发布了 0 个版本。

版本发布日期距今
5.0.2latest2022/06/064 年前
5.0.12021/08/175 年前
5.0.02020/11/175 年前
4.1.32020/02/036 年前
4.1.22019/11/266 年前
4.1.12019/07/127 年前

关于 arg 的常见问题

arg 是什么?

Unopinionated, no-frills CLI argument parser

如何安装 arg?

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

arg 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

arg 支持 ESM 还是 CommonJS?

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

arg 可以商用吗?

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

arg 的下载量有多少?

根据 npm 官方下载统计,arg 在 2026/10/05 – 2026/11/03 这 30 天内被下载 410,024,258 次,日均约 13,667,475 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

arg 还在维护吗?

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