UNPKG

2.56 kBMarkdownView Raw
1# Getopts
2[![Travis CI](https://img.shields.io/travis/getopts/getopts/master.svg)](https://travis-ci.org/getopts/getopts)
3[![Codecov](https://img.shields.io/codecov/c/github/getopts/getopts/master.svg)](https://codecov.io/gh/getopts/getopts)
4[![npm](https://img.shields.io/npm/v/getopts.svg)](https://www.npmjs.org/package/getopts)
5
6Getopts is a Node.js CLI options parser.
7
8## Installation
9
10Using npm or Yarn.
11
12<pre>
13npm i <a href="https://www.npmjs.com/package/getopts">getopts</a>
14</pre>
15
16## Usage
17
18Use getopts to parse the arguments passed into your program.
19
20```console
21$ example --jet --mode=turbo -xfv12 -- game over
22```
23
24And create an object that you can use to lookup options and values.
25
26```js
27const deepEqual = require("assert").deepEqual
28const getopts = require("getopts")
29const args = process.argv.slice(2)
30
31deepEqual(getopts(args), {
32 _: ["game", "over"],
33 jet: true,
34 mode: "turbo",
35 x: true,
36 f: true,
37 v: "12"
38})
39```
40
41Create option aliases.
42
43```js
44deepEqual(
45 getopts(args, {
46 alias: {
47 j: "jet",
48 m: "mode",
49 v: "viper"
50 }
51 }),
52 {
53 _: ["game", "over"],
54 jet: true,
55 j: true,
56 mode: "turbo",
57 m: "turbo",
58 x: true,
59 f: true,
60 v: "12",
61 viper: "12"
62 }
63)
64```
65
66Populate missing options with default values.
67
68```js
69deepEqual(
70 getopts(args, {
71 default: {
72 bolt: true,
73 hyper: 9000
74 }
75 }),
76 {
77 _: ["game", "over"],
78 jet: true,
79 mode: "turbo",
80 z: "12",
81 bolt: true,
82 hyper: 9000
83 }
84)
85```
86
87Identify options without an alias.
88
89```js
90getopts(args, {
91 alias: {
92 j: "jet",
93 m: "mode",
94 v: "viper"
95 },
96 unknown(option) {
97 throw new Error(`Unknown option: ${option}.`) // => Unknown option: x.
98 }
99})
100```
101
102## API
103
104### getopts(args, options)
105#### args
106
107An array of arguments to parse. Use [`process.argv.slice(2)`](https://nodejs.org/docs/latest/api/process.html#process_process_argv).
108
109#### options.alias
110
111An object of option aliases. An alias can be a string or an array of aliases.
112
113```js
114getopts(["-b"], {
115 alias: {
116 b: ["B", "boost"]
117 }
118}) //=> { _:[], b:true, B:true, boost:true }
119```
120
121#### options.default
122
123An object of default values for missing options.
124
125```js
126getopts(["-b"], {
127 default: {
128 super: 9000
129 }
130}) //=> { _:[], b:true, super:9000 }
131```
132
133#### options.unknown
134
135A function we run for every option without an alias. Return `false` to dismiss the option.
136
137```js
138getopts(["-xfvz"], {
139 unknown: option => option === "z"
140}) // => { _: [], z:true }
141```
142
143## License
144
145Getopts is MIT licensed. See [LICENSE](LICENSE.md).
146
147