jsflag
A quick, lightweight command-line argument and flag parser with type checking,
shorthand flags, and default values
Installation
npm install jsflag
Note: jsflag
is an ESM-only package
Usage
parse
parses command-line arguments according to the provided flag
definition object where each entry's key is a flag name and it's value is an
object describing the flag with the following properties:
- Required:
type
: A string indicating the expected type of the flag's value
('boolean'
, 'number'
, 'string'
)
- Optional:
default
: The default value assigned to the flag if no value is provided by
the end-usershorthand
: A single-letter alias that can be used with a single dash on
the command line (e.g. -p
instead of --port
)
parse
returns an object containing args
and flags
:
args
: Non-flag arguments provided by the end-userflags
: Flags with default values or values provided by the end-user
Example
node serve.js public --host 0.0.0.0 --port=8080 -d
import { parse } from 'jsflag';
const { args, flags } = parse({
host: {
type: 'string',
default: 'localhost',
shorthand: 'H',
},
port: {
type: 'number',
default: 3000,
shorthand: 'p',
},
debug: {
type: 'boolean',
default: false,
shorthand: 'd',
},
});
console.log({ args, flags });
Options
parse
can accept an object as an optional second argument to customize its
behavior. The following options are available:
argv
: An array of raw arguments to be parsed (Default: process.argv.slice(2)
)allowUnknown
: When true
, unknown flags are pushed to result.args
instead
of an error being thrown (Default: false
)stopEarly
: When true
, all arguments after the first non-flag argument are
pushed to result.args
(Default: false
)
Benchmarks
yargs-parser 25,264 ops/sec ±0.86% (91 runs sampled)
minimist 213,800 ops/sec ±3.16% (94 runs sampled)
mri 508,098 ops/sec ±0.62% (93 runs sampled)
arg 1,022,443 ops/sec ±0.82% (92 runs sampled)
jsflag 2,161,026 ops/sec ±0.45% (94 runs sampled)
See /benchmark
for benchmark details