JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 1990593
  • Score
    100M100P100Q197340F
  • License MIT

Node.js CLI options parser.

Package Exports

  • getopts

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (getopts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

Getopts

Travis CI Codecov npm

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.

Installation

Using npm or Yarn.

npm i getopts

Usage

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",
    z: "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.
  }
})

API

getopts(args, options)

args

An array of arguments to parse. Use process.argv.slice(2).

options.alias

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 }

options.default

An object of default values for missing options.

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

options.unknown

A function we run for every option without an alias. Return false to dismiss the option.

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

License

Getopts is MIT licensed. See LICENSE.