Yet another argument parser.
A tiny cli flags parser.
npm i ofi
Import:
// ESM
import { parse } from 'ofi';
// CJS
const { parse } = require('ofi');
Setup options parser:
import { parse } from 'ofi';
parse(process.argv.slice(2), {
number: ['size'],
string: ['foo', 'name', 'surname'],
boolean: ['dice', 'friendly'],
array: ['list', 'my-numbers'],
alias: { foo: ['f'] },
default: { surname: 'obama', list: [] }
});
This would give the following results:
$ node program.js --size=3 --name barack -f baz --no-dice --friendly
{
_: [],
size: 3,
name: 'barack',
surname: 'obama',
foo: 'baz',
dice: false,
list: [],
friendly: true
}
$ node program.js --list a b c -N hi there --myNumbers=13,1,2,3 -fas
{
_: ['hi', 'there'],
surname: 'obama',
list: [ 'a', 'b', 'c' ],
N: true,
'my-numbers': [ 13, 1, 2, 3 ],
foo: true,
a: true,
s: true
}
Function that parses given arguments.
Returns an argument object argv
which contains all parsed flags.
argv._
includes all arguments that weren't associated with any option.
Any argument after --
(end-of-flags) won't be parsed and will end up in argv._
and argv['--']
if populate--
option is set to true
.
Type: String | Array<String>
String or an array of strings to be parsed.
For example:
import { parse } from 'ofi';
parse(process.argv.slice(2));
Type: Object
Options for parsing given arguments.
Arguments that should be parsed as booleans.
Type: String | Array<String>
{ boolean: ['dice'] }
Booleans prefixed with --no
will be treated as negations.\
Arguments that should be parsed as strings.
Type: String | Array<String>
{ string: ['name'] }
Arguments that should be parsed as numbers.
Type: String | Array<String>
{ number: ['age'] }
Arguments that should be parsed as arrays.
Type: String | Array<String>
{ array: ['list'] }
Set default values.
Type: Object
{ default: { name: 'joe' } }
Set aliases of options.
Type: Object
{ alias: { foo: ['f'], baz: 'b' } }
Populate '--'
property in Argv
with everything after double-dash (--
, aka. end-of-flags).
Type: Boolean
Default: false
Should values that look like numbers be parsed into them.
Type: Boolean
Default: true
NOTE: This doesn't apply to flags marked as strings.
Should a group of short options be treated as seperate flags.
Example: -abc
-> { a: true, b: true, c: true }
Type: Boolean
Default: true
Convert results to camel-case.
Type: Boolean
Default: false
Custom synchronous function for parsing provided argument.
Type: Object
Default: undefined
{ coerce: { len: (arg) => arg + ' cm' } }
Callback function that runs whenever a parsed flag has not been defined in options.
Type: Function
Default: undefined
{ unknown: function (flag) { console.log('Unknown flag: "%s"', flag); } }
MIT 💖