UNPKG

2.6 kBMarkdownView Raw
1# Why a wrong args parser?
2
3> tl-dr; I didn't wrote a parser.
4
5[![Build Status](https://travis-ci.org/pateketrueke/wargs.png)](https://travis-ci.org/pateketrueke/wargs)
6[![NPM version](https://badge.fury.io/js/wargs.png)](http://badge.fury.io/js/wargs)
7[![Coverage Status](https://codecov.io/github/pateketrueke/wargs/coverage.svg)](https://codecov.io/github/pateketrueke/wargs)
8
9Instead, I used regular expressions for extracting values, flags and other kind of parameters from a string or from an argv-like array.
10
11I've tried commander, minimist, yargs, etc. but no one fulfilled my exact requirements, e.g.
12
13```js
14const str = '/ _csrf=`token` --json accept:"text/plain; charset=utf8" -- x';
15const argv = ['/', '_csrf=`token`', '--json', 'accept:text/plain; charset=utf8', '--', 'x'];
16```
17
18Both values are representing the same input, the former can be taken from any source while the latter is usually provided by `process.argv.slice(2)`, etc.
19
20Most importantly: these modules will won't work with a string as input.
21
22**wargs** will do and return: `_`, `raw`, `data`, `flags` and `params`.
23
24```js
25{
26 _: ['/'],
27 raw: ['x'],
28 data: { _csrf: '`token`' },
29 flags: { json: true },
30 params: { accept: 'text/plain; charset=utf8' },
31}
32```
33
34Hint: It suits _-and feels-_ very well on a repl for making http requests. ;-)
35
36## How it works
37
38**wargs** _understand_ regular flags, `-short` or `--long`, `[-|--]key:value` and `[-|--]key=value` params, and `everything` else will be collected as an array of values, e.g.
39
40```js
41wargs('-x').flags.x; // true
42wargs('--x').flags.x; // true
43wargs('x:y').params.x; // y
44wargs('x=y').data; // { x: 'y' }
45wargs('x y')._ // ['x', 'y']
46wargs('--x-y', { camelCase: true }).flags; // { xY: true }
47wargs('-x y', { format: v => v.toUpperCase() }).flags; // { x: 'Y' }
48```
49
50### Options
51
52- `format` — function decorator for all values
53- `arrays` — allow multiple values per single flag
54- `booleans` — allow/disable values for single booleans
55- `defaults` — apply default values for non-given flags
56- `transform` — custom callback for token processing
57- `camelCase` — normalize keys from `--camel-case` to `camelCase`
58
59### Fun facts
60
61- When I was looking for a name for this module I found that `xargs`, `yargs` and `zargs` already existed
62- I'm totally wrong on calling this module a "parser" for command line arguments, don't be rude
63- Finally, I discovered that [wargs](http://gameofthrones.wikia.com/wiki/Warg) are a thing from GoT
64
65![OrellWarg](http://vignette2.wikia.nocookie.net/gameofthrones/images/f/fc/OrellWarg.jpg/revision/latest)