dashdash
A light, featureful and explicit option parsing library for node.js.
Why another one? See below. tl;dr: The others I've tried are one of too loosey goosey (not explicit), too big/too many deps, or ill specified. YMMV.
Follow @trentmick for updates to node-dashdash.
Install
Usage
Longer Example
A more realistic starter script "foo.js" is as follows. This also shows using parser.help()
for formatted option help.
Some example output from this script (foo.js):
See the "examples" dir for a number of starter examples using some of dashdash's features.
Environment variable integration
If you want to allow environment variables to specify options to your tool, dashdash makes this easy. We can change the 'verbose' option in the example above to include an 'env' field:
then the "FOO_VERBOSE" environment variable can be used to set this option:
Boolean options will interpret the empty string as unset, '0' as false and anything else as true.
Non-booleans can be used as well. Strings:
Numbers:
With the includeEnv: true
config to parser.help()
the environment variable can also be included in help output:
Bash completion
Dashdash provides a simple way to create a Bash completion file that you can place in your "bash_completion.d" directory -- sometimes that is "/usr/local/etc/bash_completion.d/"). Features:
Support for short and long opts
Support for knowing which options take arguments
Support for subcommands (e.g. 'git log ' to show just options for the log subcommand). See node-cmdln for how to integrate that.
Does the right thing with "--" to stop options.
Custom optarg and arg types for custom completions.
Dashdash will return bash completion file content given a parser instance:
or directly from a options
array of options specs:
Write that content to "/usr/local/etc/bash_completion.d/mycli" and you will have Bash completions for mycli
. Alternatively you can write it to any file (e.g. "~/.bashrc") and source it.
You could add a --completion
hidden option to your tool that emits the completion content and document for your users to call that to install Bash completions.
See examples/ddcompletion.js for a complete example, including how one can define bash functions for completion of custom option types. Also see node-cmdln for how it uses this for Bash completion for full multi-subcommand tools.
TODO: document specExtra
TODO: document includeHidden
TODO: document custom types,
function complete\_FOO
guide, completionTypeTODO: document argtypes
Parser config
Parser construction (i.e. dashdash.createParser(CONFIG)
) takes the following fields:
options
(Array of option specs). Required. See the Option specs section below.interspersed
(Boolean). Optional. Default is true. If true this allows interspersed arguments and options. I.e.:Set it to false to have '-h' not get parsed as an option in the above example.
allowUnknown
(Boolean). Optional. Default is false. If false, this causes unknown arguments to throw an error. I.e.:Set it to true to treat the unknown option as a positional argument.
Caveat: When a shortopt group, such as
-xaz
contains a mix of known and unknown options, the entire group is passed through unmolested as a positional argument.Consider if you have a known short option
-a
, and parse the following command line:where
-x
and-z
are unknown. There are multiple ways to interpret this:-x
takes a value:{x: 'az'}
-x
and-z
are both booleans:{x:true,a:true,z:true}
Since dashdash does not know what
-x
and-z
are, it can't know if you'd prefer to receive{a:true,_args:['-x','-z']}
or{x:'az'}
, or{_args:['-xaz']}
. Leaving the positional arg unprocessed is the easiest mistake for the user to recover from.
Option specs
Example using all fields (required fields are noted):
Each option spec in the options
array must/can have the following fields:
name
(String) ornames
(Array). Required. These give the option name and aliases. The first name (if more than one given) is the key for the parsedopts
object.type
(String). Required. One of:bool
string
number
integer
positiveInteger
date (epoch seconds, e.g. 1396031701, or ISO 8601 format
YYYY-MM-DD[THH:MM:SS[.sss][Z]]
, e.g. "2014-03-28T18:35:01.489Z")arrayOfBool
arrayOfString
arrayOfNumber
arrayOfInteger
arrayOfPositiveInteger
arrayOfDate
FWIW, these names attempt to match with asserts on assert-plus. You can add your own custom option types with
dashdash.addOptionType
. See below.completionType
(String). Optional. This is used for Bash completion for an option argument. If not specified, then the value oftype
is used. Any string may be specified, but only the following values have meaning:none
: Provide no completions.file
: Bash's default completion (i.e.complete -o default
), which includes filenames.Any string FOO for which a
function complete_FOO
Bash function is defined. This is for custom completions for a given tool. Typically these custom functions are provided in thespecExtra
argument todashdash.bashCompletionFromOptions()
. See "examples/ddcompletion.js" for an example.
env
(String or Array of String). Optional. An environment variable name (or names) that can be used as a fallback for this option. For example, given a "foo.js" like this:Both
node foo.js --dry-run
andFOO_DRY_RUN=1 node foo.js
would result inopts.dry_run = true
.An environment variable is only used as a fallback, i.e. it is ignored if the associated option is given in
argv
.help
(String). Optional. Used forparser.help()
output.helpArg
(String). Optional. Used in help output as the placeholder for the option argument, e.g. the "PATH" in:helpWrap
(Boolean). Optional, default true. Set this tofalse
to have that option'shelp
not be text wrapped in<parser>.help()
output.default
. Optional. A default value used for this option, if the option isn't specified in argv.hidden
(Boolean). Optional, default false. If true, help output will not include this option. See also theincludeHidden
option tobashCompletionFromOptions()
for Bash completion.
Option group headings
You can add headings between option specs in the options
array. To do so, simply add an object with only a group
property -- the string to print as the heading for the subsequent options in the array. For example:
Note: You can use an empty string, {group: ''}
, to get a blank line in help output between groups of options.
Help config
The parser.help(...)
function is configurable as follows:
indent
(Number or String). Default 4. Set to a number (for that many spaces) or a string for the literal indent.headingIndent
(Number or String). Default half length ofindent
. Set to a number (for that many spaces) or a string for the literal indent. This indent applies to group heading lines, between normal option lines.nameSort
(String). Default is 'length'. By default the names are sorted to put the short opts first (i.e. '-h, --help' preferred to '--help, -h'). Set to 'none' to not do this sorting.maxCol
(Number). Default 80. Note that reflow is just done on whitespace so a long token in the option help can overflow maxCol.helpCol
(Number). If not set a reasonable value will be determined betweenminHelpCol
andmaxHelpCol
.minHelpCol
(Number). Default 20.maxHelpCol
(Number). Default 40.helpWrap
(Boolean). Default true. Set tofalse
to have optionhelp
strings not be textwrapped to the helpCol..maxCol range.includeEnv
(Boolean). Default false. If the option has associated environment variables (via theenv
option spec attribute), then append mentioned of those envvars to the help string.includeDefault
(Boolean). Default false. If the option has a default value (via thedefault
option spec attribute, or a default on the option's type), then a "Default: VALUE" string will be appended to the help string.
Custom option types
Dashdash includes a good starter set of option types that it will parse for you. However, you can add your own via:
For example, a simple option type that accepts 'yes', 'y', 'no' or 'n' as a boolean argument would look like:
See "examples/custom-option-*.js" for other examples. See the addOptionType
block comment in "lib/dashdash.js" for more details. Please let me know with an issue if you write a generally useful one.
Why
Why another node.js option parsing lib?
nopt
really is just for "tools like npm". Implicit opts (e.g. '--no-foo' works for every '--foo'). Can't disable abbreviated opts. Can't do multiple usages of same opt, e.g. '-vvv' (I think). Can't do grouped short opts.optimist
has surprise interpretation of options (at least to me). Implicit opts mean ambiguities and poor error handling for fat-fingering.process.exit
calls makes it hard to use as a libary.optparse
Incomplete docs. Is this an attempted clone of Python'soptparse
. Not clear. Some divergence.parser.on("name", ...)
API is weird.argparse
Dep on underscore. No thanks just for option processing.find lib | wc -l
->26
. Overkill. Argparse is a bit different anyway. Not sure I want that.posix-getopt
No type validation. Though that isn't a killer. AFAIK can't have a long opt without a short alias. I.e. nogetopt_long
semantics. Also, no whizbang features like generated help output."commander.js": I wrote a critique a while back. It seems fine, but last I checked had an outstanding bug that would prevent me from using it.
License
MIT. See LICENSE.txt.
Last updated