Node.js CLI options parser.
JavaScript
Switch branches/tags
Latest commit 3cbbbf9 Nov 12, 2017 @JorgeBucaran JorgeBucaran 2.0.0

README.md

Getopts

Travis CI Codecov npm

Getopts is a Node.js CLI options parser.

Installation

Using npm or Yarn.

npm i getopts

Usage

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

$ example/demo --super=sonic -jb9000 -- game over
const options = getopts(process.argv.slice(2), {
  alias: {
    s: "super",
    b: "blitz"
  },
  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"],
  j: true,
  s: "sonic",
  b: "9000",
  super: "sonic",
  blitz: "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(["-b"], {
  alias: {
    b: ["B", "turbo"]
  }
}) //=> { _:[], b:true, B:true, turbo:true }

options.boolean

An array of options that should be parsed as booleans.

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

options.default

An object of default values for missing options.

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

options.unknown

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

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

License

Getopts is MIT licensed. See LICENSE.