What is getopts?
The getopts npm package is a lightweight and fast option parser for Node.js. It is used to parse command-line options and arguments in a simple and efficient manner.
What are getopts's main functionalities?
Basic Option Parsing
This feature allows you to parse command-line options and arguments. The code sample demonstrates how to use getopts to parse the command-line arguments passed to a Node.js script.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2));
console.log(options);
Default Values
This feature allows you to set default values for options. The code sample shows how to provide default values for the 'name' and 'age' options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
default: {
name: 'defaultName',
age: 25
}
});
console.log(options);
Aliases
This feature allows you to define aliases for options. The code sample demonstrates how to set up aliases for the 'name' and 'age' options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
alias: {
n: 'name',
a: 'age'
}
});
console.log(options);
Boolean Options
This feature allows you to specify which options should be treated as boolean. The code sample shows how to define 'verbose' and 'debug' as boolean options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
boolean: ['verbose', 'debug']
});
console.log(options);
Unknown Option Handling
This feature allows you to handle unknown options. The code sample demonstrates how to log an error message for unknown options and prevent them from being included in the parsed options.
const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
unknown: (option) => {
console.error(`Unknown option: ${option}`);
return false;
}
});
console.log(options);
Other packages similar to getopts
minimist
Minimist is a popular option parser for Node.js that is similar to getopts. It provides a simple way to parse command-line arguments and supports features like default values, aliases, and boolean options. Compared to getopts, minimist is more widely used and has a larger community.
yargs
Yargs is a powerful option parser for Node.js that offers a rich set of features for building command-line tools. It supports advanced features like command handling, middleware, and interactive prompts. Yargs is more feature-rich compared to getopts, making it suitable for more complex CLI applications.
commander
Commander is a comprehensive option parser and command-line interface (CLI) framework for Node.js. It provides a robust set of features for defining commands, options, and arguments. Commander is more feature-complete compared to getopts and is ideal for building complex CLI applications with multiple commands.
Getopts
Getopts is a Node.js CLI arguments parser. It's designed closely following the Utility Syntax Guidelines so that your programs behave like typical UNIX utilities effortlessly and without sacrificing developer experience.
Need for speed? Getopts is the fastest CLI parser for Node.js
Installation
npm i getopts
Usage
Use getopts to parse the command-line arguments passed to your program.
You can find the arguments in the process.argv
array. The first element will be the path to the node executable, followed by the path to the file being executed. The remaining elements will be the command line arguments. We don't need the first two elements, so we'll extract everything after.
$ example/demo --turbo -xw10 -- alpha beta
const getopts = require("getopts")
const options = getopts(process.argv.slice(2), {
alias: {
w: "warp",
t: "turbo"
}
})
Getopts takes an array of arguments (and optional options object) and returns an object that maps argument names to values. This object can be used to look up the value of an option by its name. The underscore _
is reserved for operands. Operands include standalone arguments (non-options), the single dash -
and every argument after a double-dash --
.
{
_: ["alpha", "beta"],
w: 10,
x: true,
t: true,
warp: 10,
turbo: true
}
Parsing Rules
Short Options
-
A short option consists of one dash -
followed by a single alphabetic character. Multiple options can be clustered together without spaces. Short options are cast to boolean unless followed by an operand or adjacent to one or more non-alphabetic characters matching the regular expression /[!-@[-`{-~][\s\s]*/.
getopts(["-ab", "-c"])
getopts(["-a", "alpha"])
getopts(["-abc1"])
-
Only the last character in a cluster of options can be parsed as boolean, string or number depending on the argument that follows it. Any characters preceding it will be true
. You can use opts.string to indicate if one of these options should be parsed as a string instead.
getopts(["-abc-100"], {
string: ["b"]
})
-
The argument immediately following a short or long option which is not an option itself will be used as a value. You can use opts.boolean to indicate the option should be parsed as boolean and treat the value as an operand.
getopts(["-a", "alpha"], {
boolean: ["a"]
})
-
Any character listed in the ASCII table can be used as a short option if it's the first character after the dash.
getopts(["-9", "-#10", "-%0.01"])
Long Options
-
A long option consists of two dashes --
followed by one or more characters. Any character listed in the ASCII table can be used to form a long option with the exception of the =
symbol which separates an option's name and value.
getopts(["--turbo", "--warp=10"])
getopts(["--warp=e=mc^2"])
getopts(["----", "alpha"])
-
Arguments can be negated if prefixed with the sequence --no-
. Their value is always false
.
getopts(["--no-turbo"])
Operands
-
Every argument after the first double-dash --
is saved to the operands array _
.
getopts(["--", "--alpha", "001"])
-
Every non-option, standalone argument is an operand.
getopts(["alpha", "-w9"])
getopts(["--code=alpha", "beta"])
-
A standalone dash -
is an operand.
getopts(["--turbo", "-"])
Other
-
Options missing from the arguments array that have been designated as a boolean or string type will be added to the result object as false
and ""
respectively.
getopts([], {
string: ["a"],
boolean: ["b"]
})
-
The string false is always cast to boolean.
getopts(["--turbo=false"])
-
Options that appear multiple times are represented as an array of every value in the order they are found.
getopts(["-a?alpha=beta", "-aa0.1"]
-
A value may contain newlines or other control characters.
getopts(["--text=top\n\tcenter\bottom"])
API
getopts(argv, opts)
argv
An array of arguments to parse, e.g., process.argv
.
Arguments prefixed with one or two dashes are referred to as short and long options respectively. Options can have one or more aliases. Numerical values are cast to numbers when possible.
opts.alias
An object of option aliases. An alias can be a string or an array of strings. Aliases let you define alternate names for an option, e.g., the short and long (canonical) variations.
getopts(["-t"], {
alias: {
turbo: ["t", "T"]
}
})
opts.boolean
An array of options to be parsed as booleans. In the example, defining t
as boolean causes the following argument to be parsed as an operand and not as a value.
getopts(["-t", "alpha"], {
boolean: ["t"]
})
opts.string
An array of options to be parsed as strings. In the example, by defining t
as string, the remaining characters are parsed as a value and not as individual options.
getopts(["-atabc"], {
string: ["t"]
})
opts.default
An object of default values for options not present in the arguments array.
getopts(["--warp=10"], {
default: {
warp: 15,
turbo: true
}
})
opts.unknown
A function to be run for every unknown option. Return false
to dismiss the option. Unknown options are those that appear in the arguments array but are not present in opts.string, opts.boolean, opts.default or opts.alias.
getopts(["-abc"], {
unknown: option => "a" === option
})
Benchmark Results
All tests run on a 2.4GHz Intel Core i7 CPU with 16 GB memory.
npm i -C bench && node bench
mri × 378,898 ops/sec
yargs × 32,993 ops/sec
getopts × 1,290,267 ops/sec
minimist × 289,048 ops/sec
License
Getopts is MIT licensed. See LICENSE.