• Stars
    star
    633
  • Rank 71,037 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Node.js CLI options parser

Getopts

Parse CLI arguments.

  • Lightweight drop-in replacement for minimist and clones.
  • Small (180 LOC), focused, no dependencies.
  • Up to 6x faster than alternatives!

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.

{
  _: ["index.js", "package.json"],
  output: "main.js",
  type: "module",
  o: "main.js",
  f: "main.js",
  t: "module",
}

Installation

npm install getopts

Parsing rules

Short options

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:

getopts(["-ab", "-c"]) //=> { _: [], a:true, b:true, c:true }
getopts(["-a", "alpha"]) //=> { _: [], a:"alpha" }
getopts(["-abc1"]) //=> { _: [], a:true, b:true, c:1 }

Use opts.string to parse an option as a string regardless.

getopts(["-kF12"], {
  string: ["k"],
}) //=> { _: [], k:"F12" }

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.

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

Any character listed in the ASCII table can be used as a short option if it's the first character after the dash.

getopts(["-9", "-#10", "-%0.01"]) //=> { _:[], 9:true, #:10, %:0.01 }

Long options

A long option consists of a -- followed by a name and a value separated by an =. Long options without a value are boolean by default.

getopts(["--turbo", "--warp=10"]) //=> { _: [], turbo:true, warp:10 }
getopts(["--warp=e=mc^2"]) //=> { _: [], warp:"e=mc^2" }
getopts(["--@", "alpha"]) //=> { _: [], @:"alpha" }

Negated options start with --no- and are always false.

getopts(["--no-turbo"]) //=> { _: [], turbo:false }

Operands

Every non-option argument is an operand. Operands are saved to the result._ operands array.

getopts(["alpha", "-w9", "bravo"]) //=> { _: ["alpha", "bravo"], w:9 }
getopts(["--code=alpha", "bravo"]) //=> { _: ["bravo"], code:"alpha" }

Everything after a standalone -- is an operand.

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

A single - is also treated as an operand.

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

Other

Options specified as boolean or string will be added to the result object as false or "" (even if missing from the arguments array).

getopts([], {
  string: ["a"],
  boolean: ["b"],
}) //=> { _:[], a:"", b:false }

Repeated options are stored as arrays with every value in order of appearance.

getopts(["-x?alpha=bravo", "-x3.14", "-x"] //=> { _:[], a:["?alpha=bravo", 3.14, true] }

A value may contain newlines or other control characters.

getopts(["--text=top\n\tbottom"]) //=> { _:[], text:"top\n\tbottom" }

="false" is converted to boolean by default.

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

API

getopts(argv, opts)

Parse command-line arguments. Returns an object mapping argument names to their values.

argv[]

An array of arguments, usually process.argv.

opts.alias

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.

getopts(["-t"], {
  alias: {
    turbo: ["t", "T"],
  },
}) //=> { _:[], t:true, T:true, turbo:true }

opts.boolean

An array of options to parse as boolean. In the example below, t is parsed as a boolean, causing the following argument to be treated as an operand.

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

opts.string

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.

getopts(["-atabc"], {
  string: ["t"],
}) //=> { _:[], a:true, t:"abc" }

opts.default

An object of default values for options not present in the arguments array.

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

opts.unknown()

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.

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

opts.stopEarly

A boolean property. If true, the operands array _ will be populated with all the arguments after the first operand.

getopts(["-w9", "alpha", "--turbo", "bravo"], {
  stopEarly: true,
}) //=> { _:["alpha", "--turbo", "bravo"], w:9 }

This property is useful when implementing sub-commands in a CLI.

import getopts from "getopts"
import { install, update, uninstall } from "./commands.js"

const options = getopts(process.argv.slice(2), {
  stopEarly: true,
})

const [command, subargv] = options._

if (command === "install") {
  install(subargv)
} else if (command === "update") {
  update(subargv)
} else if (command === "uninstall") {
  uninstall(subargv)
}

Benchmarks

npm --prefix bench start

License

MIT

More Repositories

1

hyperapp

1kB-ish JavaScript framework for building hypertext applications
JavaScript
19,043
star
2

fisher

A plugin manager for Fish
Shell
7,560
star
3

awsm.fish

A curation of prompts, plugins & other Fish treasures πŸšπŸ’Ž
4,066
star
4

nvm.fish

The Node.js version manager you'll adore, crafted just for Fish
Shell
2,033
star
5

cookbook.fish

From Shell to Plate: Savor the Zest of Fish 🦞
2,002
star
6

colorette

🌈Easily set your terminal text color & styles
JavaScript
1,595
star
7

superfine

Absolutely minimal view layer for building web interfaces
JavaScript
1,564
star
8

classcat

Build a class attribute string quickly
JavaScript
905
star
9

hydro

Ultra-pure, lag-free prompt with async Git statusβ€”just for Fish
Shell
609
star
10

hyperawesome

A curated list of awesome projects built with Hyperapp + more
492
star
11

replay.fish

Run Bash commands, replay changes in Fish 🍀
Shell
392
star
12

twist

Declarative JavaScript Testing
JavaScript
378
star
13

autopair.fish

Auto-complete matching pairs in the Fish command line
Shell
369
star
14

fishtape

100% pure-Fish test runner
Shell
345
star
15

spark.fish

β–β–‚β–„β–†β–‡β–ˆβ–‡β–†β–„β–‚β–
Shell
335
star
16

hyperapp-router

Declarative routing for Hyperapp V1 using the History API.
JavaScript
257
star
17

getopts.fish

Parse CLI options in Fish
Shell
220
star
18

gitio.fish

Create a custom git.io URL
Shell
88
star
19

hyperapp-html

Html helper functions for Hyperapp V1
JavaScript
81
star
20

pyenv

Pyenv support plugin for fish-shell
Shell
62
star
21

humantime.fish

Turn milliseconds into a human-readable string in Fish
Shell
21
star
22

.github

My health files
1
star
23

jorgebucaran.github.io

HTML
1
star