Getopts is a Node.js CLI options parser.
- Swift: Getopts is 10 to 1000 times faster than the alternatives. See benchmarks for details.
- Familiar: Getopts works similarly to other CLI parsers like mri, yargs and minimist.
- Predictable: Getopts is designed according to the Utility Syntax Guidelines.
Using npm or Yarn.
npm i getopts
Use Getopts to parse the arguments passed into your program.
$ example/demo --jet --mode=turbo -xfv12 -- game over
And create an object that you can use to lookup options and values.
const deepEqual = require("assert").deepEqual
const getopts = require("getopts")
const args = process.argv.slice(2)
deepEqual(getopts(args), {
_: ["game", "over"],
jet: true,
mode: "turbo",
x: true,
f: true,
v: "12"
})
Create option aliases.
deepEqual(
getopts(args, {
alias: {
j: "jet",
m: "mode",
v: "viper"
}
}),
{
_: ["game", "over"],
jet: true,
j: true,
mode: "turbo",
m: "turbo",
x: true,
f: true,
v: "12",
viper: "12"
}
)
Populate missing options with default values.
deepEqual(
getopts(args, {
default: {
bolt: true,
hyper: 9000
}
}),
{
_: ["game", "over"],
jet: true,
mode: "turbo",
v: "12",
bolt: true,
hyper: 9000
}
)
Identify options without an alias.
getopts(args, {
alias: {
j: "jet",
m: "mode",
v: "viper"
},
unknown(option) {
throw new Error(`Unknown option: ${option}.`) // => Unknown option: x.
}
})
An array of arguments to parse. Use process.argv.slice(2)
.
An object of option aliases. An alias can be a string or an array of aliases.
getopts(["-b"], {
alias: {
b: ["B", "boost"]
}
}) //=> { _:[], b:true, B:true, boost:true }
An object of default values for missing options.
getopts(["-b"], {
default: {
super: 9000
}
}) //=> { _:[], b:true, super:9000 }
A function we run for every option without an alias. Return false
to dismiss the option.
getopts(["-xfvz"], {
unknown: option => option === "z"
}) // => { _: [], z:true }
Getopts is MIT licensed. See LICENSE.