Break up command-line arguments into key-value pairs for easy look-up and retrieval. Built upon utility conventions that have been used for decades, Getopts sane defaults help you write CLI tools that look and feel like the real deal.
$ example --type=module -o main.js *.{js,json}
import getopts from "getopts"const options = getopts(process.argv.
slice
(
2
), {
alias: {
output: ["o", "f"],
type: "t",
},
})
The result is an object populated with all the parsed arguments.
A short option consists of a - followed by a single alphabetic character. Multiple options can be grouped together without spaces. Short options are boolean by default unless followed by an operand (non-option) or if adjacent to any non-alphabetic characters:
The first operand following an option will be used as its value. Use opts.boolean to specify that an option should be parsed as a boolean regardless, causing the following argument to be treated as an operand instead.
An object of option aliases. An alias can be a string or an array of strings. Aliases let you declare substitute names for an option, e.g., the short (abbreviated) and long (canonical) variations.
An array of flags to parse as strings. In the example below, t is parsed as a string, causing all adjacent characters to be treated as a single value and not as individual options.
We call this function for each unknown option. Return false to discard the option. Unknown options are those that appear in the arguments array, but are not in opts.string, opts.boolean, opts.default, or opts.alias.