Node.js CLI options parser.
JavaScript
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
bench
example
test
.gitignore
.travis.yml
LICENSE.md
README.md
index.js
package.json

README.md

Getopts

Travis CI Codecov npm

Getopts is a Node.js CLI options parser. It's designed according to the Utility Conventions so that your programs behave like typical UNIX utilities effortlessly — without sacrificing developer experience.

Need for speed? Getopts is optimized for runtime performance and runs 10 to 20 times faster than alternatives according to our benchmarks.

Installation

npm i getopts

Usage

Use getopts to parse the arguments passed into your program from the command line.

$ example/demo --super=sonic -au9000 -- game over
const getopts = require("getopts")

const options = getopts(process.argv.slice(2), {
  alias: {
    s: "super",
    u: "ultra"
  },
  default: {
    turbo: true
  }
})

Getopts expects an array of arguments and options object (optional) and returns an object where you can look up the argument keys and their values.

{
  _: ["game", "over"],
  a: true,
  s: "sonic",
  u: "9000",
  super: "sonic",
  ultra: "9000",
  turbo: true
}

API

getopts(argv, options)

argv

An array of arguments to parse. See process.argv.

Arguments that begin with one or two dashes are called options or flags. Options may have one or more aliases. The underscore key stores operands. Operands include non-options, the single dash - and all the arguments after --.

options.alias

An object of option aliases. An alias can be a string or an array of strings.

getopts(["-u"], {
  alias: {
    u: ["U", "ultra"]
  }
}) //=> { _:[], u:true, U:true, ultra:true }

options.boolean

An array of options that should be parsed as booleans. In the example, by indicating that u is a boolean option, the number 1 is parsed as an operand and not as a value.

getopts(["-u", 1], {
  boolean: ["u"]
}) //=> { _:[1], u:true }

options.default

An object of default values for missing options.

getopts(["-u"], {
  default: {
    turbo: true
  }
}) //=> { _:[], u:true, turbo:true }

options.unknown

A function that runs for every unknown option. Return false to dismiss the option.

getopts(["-abc"], {
  unknown: option => "a" === option
}) // => { _:[], a:true }

License

Getopts is MIT licensed. See LICENSE.