Socket
Socket
Sign inDemoInstall

arg

Package Overview
Dependencies
0
Maintainers
21
Versions
14
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    arg

Another simple argument parser


Version published
Weekly downloads
27M
decreased by-8.86%
Maintainers
21
Install size
9.62 kB
Created
Weekly downloads
 

Package description

What is arg?

The arg npm package is a simple argument parsing library. It allows developers to parse command-line arguments in Node.js applications into a structured format that is easy to work with. It supports various types of flags and options, including boolean flags, string options, and number options.

What are arg's main functionalities?

Parsing command-line flags and options

This feature allows the parsing of command-line arguments with various types of expected values. The example code demonstrates how to define the expected types for each flag and option, including boolean, count, number, and string types, as well as how to set up aliases for shorthand notation.

{"const arg = require('arg');\n\nconst args = arg({\n  // Types\n  '--help': Boolean,\n  '--version': Boolean,\n  '--verbose': arg.COUNT, // A count of how many times the flag was set\n  '--port': Number, // A port number\n  '--name': String, // A string name\n  // Aliases\n  '-h': '--help',\n  '-v': '--version',\n  '-n': '--name'\n});\n\nconsole.log(args); // Output the parsed arguments"}

Handling default values

This feature allows developers to specify default values for command-line options that are not provided by the user. The example code shows how to set default values for a port and host.

{"const arg = require('arg');\n\nconst args = arg({\n  '--port': Number,\n  '--host': String\n}, {\n  // Default values\n  '--port': 8080,\n  '--host': 'localhost'\n});\n\nconsole.log(args); // Output the parsed arguments with defaults"}

Permissive parsing

This feature enables permissive parsing, which means that the parser will ignore any flags that are not explicitly defined in the schema. The example code shows how to enable permissive parsing.

{"const arg = require('arg');\n\nconst args = arg({\n  '--port': Number,\n  '--host': String\n}, {\n  permissive: true\n});\n\nconsole.log(args); // Output the parsed arguments, ignoring any non-specified flags"}

Other packages similar to arg

Readme

Source

Arg

arg is yet another command line option parser.

Installation

Use Yarn or NPM to install.

$ yarn add arg

or

$ 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)})

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');

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

For example:

$ node ./hello.js --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,
	'--port':    Number,      // --port <number> or --port=<number>
	'--name':    String,      // --name <string> or --name=<string>
	'--tag':     [String],    // --tag <string> or --tag=<string>

	// Aliases
	'-v':        '--version',
	'-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,
	'--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 operatons or for supporting -v multiple times, etc.)

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

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
}
Errors
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

License

Copyright © 2017-2018 by ZEIT, Inc. Released under the MIT License.

FAQs

Last updated on 14 Dec 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc