cheatsheets/minimist.md

83 lines
1.4 KiB
Markdown
Raw Permalink Normal View History

2014-08-04 01:54:34 +00:00
---
title: minimist
2015-11-24 05:02:17 +00:00
category: JavaScript libraries
2014-08-04 01:54:34 +00:00
---
2017-10-15 06:47:53 +00:00
### Usage
2014-08-04 01:54:34 +00:00
```js
2015-11-15 00:05:57 +00:00
var minimist = require('minimist')
2017-10-15 06:47:53 +00:00
```
{: .-setup}
```js
var args = minimist(process.argv.slice(2), {
string: 'lang', // --lang xml
boolean: ['version'], // --version
alias: { v: 'version' }
})
```
```js
console.log(args)
```
2015-11-15 00:05:57 +00:00
2017-10-15 06:47:53 +00:00
All options are optional, but it's recommended you set `string` and `boolean` at least.
### All options
```js
2015-11-15 00:05:57 +00:00
var args = minimist(process.argv.slice(2), {
2017-10-15 06:47:53 +00:00
string: [ 'lang' ],
boolean: [ 'pager' ],
2015-11-15 00:05:57 +00:00
alias: { h: 'help', v: 'version' },
default: { lang: 'en' },
'--': true,
stopEarly: true, /* populate _ with first non-option */
unknown: function () { ... } /* invoked on unknown param */
2017-10-15 06:47:53 +00:00
})
```
2014-08-04 01:54:34 +00:00
2017-10-15 06:47:53 +00:00
All options are optional.
### Result
With `--lang xml --no-pager -h index.js package.json`, you get:
{: .-setup}
```
2014-08-04 01:54:34 +00:00
args == {
2015-11-15 00:05:57 +00:00
lang: 'xml',
2017-10-15 06:47:53 +00:00
version: false,
2015-11-15 00:05:57 +00:00
h: true,
help: true,
2014-08-04 01:54:34 +00:00
_: [ 'index.js', 'package.json' ]
}
```
2017-10-15 06:47:53 +00:00
## Meow
2015-11-15 00:05:57 +00:00
### Help and version
2014-08-12 04:03:16 +00:00
2017-10-15 06:47:53 +00:00
Use [meow](https://www.npmjs.com/package/meow) to automatically add support for `--help`, `--version` and more.
{: .-setup}
2014-08-12 04:03:16 +00:00
2015-11-15 00:05:57 +00:00
```js
meow(`
Usage:
$0 FILES [options]
Options:
-h, --help print usage information
-v, --version show version info and exit
`, {
2017-10-15 06:47:53 +00:00
alias: { h: 'help', v: 'version' }
/* minimist options */
2015-11-15 00:05:57 +00:00
})
2014-08-12 04:03:16 +00:00
```
2014-08-04 01:54:34 +00:00
### Reference
2017-10-15 06:47:53 +00:00
* <https://www.npmjs.org/package/minimist>
* <https://github.com/substack/minimist>