Skip to content

axtk/args-json

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

args-json

Zero-dependency typed command-line argument parser

Installation

npm i args-json

Usage

import {parseArgs} from 'args-json';

let args = parseArgs('--config=./config.json -v 1.5.12 -d "lorem ipsum" -i -n=0 --test-value qwe --debug', {
    v: 'version',
    d: 'description',
});
// args = {
//     config: './config.json',
//     version: '1.5.12',
//     description: 'lorem ipsum',
//     i: true,
//     n: 0,
//     testValue: 'qwe',
//     debug: true,
// };

Note that keys and values can be separated from each other either with a space or an equals sign, and the value can be either quoted or not. These variants are equivalent. Also, keys are converted to camelCase (like --test-valuetestValue in the example above).

The second parameter is optional. It is a way to rename argument keys in the output. In the example above, -d and -v in the input string are renamed to description and version in the output object.

String input

let args = parseArgs('--config ./configs/default.json --debug');
// {config: './configs/default.json', debug: true}

if (args.debug)
    console.log(args.config);

The first line is also equivalent to:

let args = parseArgs('--config "./configs/default.json" --debug');

or

let args = parseArgs('--config=./configs/default.json --debug');

or

let args = parseArgs('--config="./configs/default.json" --debug');

String array input

let args = parseArgs(['--config', './configs/default.json', '--debug']);
// {config: './configs/default.json', debug: true}

if (args.debug)
    console.log(args.config);

Node process arguments

In a Node environment, parseArgs() without parameters parses the node process arguments.

let args = parseArgs();

is equivalent to

let args = parseArgs(process.argv);

Key mapping

let args = parseArgs('-c ./configs/default.json --debug', {c: 'config'});
// {config: './configs/default.json', debug: true}

if (args.debug)
    console.log(args.config);

As specified with the second parameter of parseArgs(), -c is mapped to config in the output.

Value parsing

Values are JSON.parsed if they are parsable.

let args = parseArgs('-d \'{"x":10}\' -i 0 -n=3 -c ./config.json');
// {d: {x: 10}, i: 0, n: 3, c: './config.json'}

Typing

The output type can be specified by providing a generic type to parseArgs<T>().

type CustomShape = {
    level?: number;
    debug?: boolean;
};

let args = parseArgs<CustomShape>('--level=0 --debug');

if (args.debug)
    console.log(`Level: ${args.level}`);