The simplest CLI arguments parser.
npm install --save-prod argcat
Usage
import { parseArgs } from 'argcat';
const options = parseArgs(process.argv.slice(2));
Arguments prefixed with a '--'
are treated as options:
parseArgs(['--foo']);
Options can have values:
parseArgs(['--foo', 'bar']);
parseArgs(['--foo', '--qux', 'bar']);
If an option is repeated multiple times then all values are captured in an array:
parseArgs(['--foo', 'bar', '--foo', 'qux']);
Arguments that aren't prefixed with minus chars are stored under ''
key:
parseArgs(['foo', 'bar']);
There's a special option '--'
, after which all arguments are stored under '--'
key:
parseArgs(['--', '--foo', 'bar']);
Mark an option as a flag to prevent value capturing:
parseArgs(['--foo', 'bar']);
parseArgs(['--foo', 'bar'], { flags: ['foo'] });
Flag options have true
value instead of an array.
Shorthands
By default, shorthand options are ignored:
parseArgs(['-x']);
To preserve shorthands, use keepShorthands
option:
parseArgs(['-x'], { keepShorthands: true });
Multiple shorthands can be combined:
parseArgs(['-abc'], { keepShorthands: true });
Use shorthand
mapping to expand shorthands:
parseArgs(['-x'], { shorthands: { x: 'foo' } });
Shorthand options can have values:
parseArgs(['-x', 'bar'], { keepShorthands: true });
parseArgs(['-abc', 'bar'], { keepShorthands: true });
Commands
argcat doesn't have a special treatment for commands syntax, but it can be easily emulated:
const argv = ['push', '--tags'];
const result = parseArgs(argv, { flags: ['tags'] });
The first element of ''
is a command:
const command = result[''].shift();
if (command === 'push') {
}
Note that this approach allows user to specify options before the command:
const result = parseArgs(['--tags', 'push'], { flags: ['tags'] });
Type coercion
Combine argcat with Doubter to validate parsed arguments and to coerce
their types.
import { parseArgs } from 'argcat';
import * as d from 'doubter';
const optionsShape = d
.object({
age: d.number()
})
.strip();
const options = optionsShape.parse(
parseArgs(['--age', '42']),
{ coerce: true }
);
Cat by Laura Graves