Home

Awesome

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.

Install

npm install dashdash

Active Versions

Usage

var dashdash = require('dashdash');

// Specify the options. Minimally `name` (or `names`) and `type`
// must be given for each.
var options = [
    {
        // `names` or a single `name`. First element is the `opts.KEY`.
        names: ['help', 'h'],
        // See "Option specs" below for types.
        type: 'bool',
        help: 'Print this help and exit.'
    }
];

// Shortcut form. As called it infers `process.argv`. See below for
// the longer form to use methods like `.help()` on the Parser object.
var opts = dashdash.parse({options: options});

console.log("opts:", opts);
console.log("args:", opts._args);

Longer Example

A more realistic starter script "foo.js" is as follows. This also shows using parser.help() for formatted option help.

var dashdash = require('dashdash');

var options = [
    {
        name: 'version',
        type: 'bool',
        help: 'Print tool version and exit.'
    },
    {
        names: ['help', 'h'],
        type: 'bool',
        help: 'Print this help and exit.'
    },
    {
        names: ['verbose', 'v'],
        type: 'arrayOfBool',
        help: 'Verbose output. Use multiple times for more verbose.'
    },
    {
        names: ['file', 'f'],
        type: 'string',
        help: 'File to process',
        helpArg: 'FILE'
    }
];

var parser = dashdash.createParser({options: options});
try {
    var opts = parser.parse(process.argv);
} catch (e) {
    console.error('foo: error: %s', e.message);
    process.exit(1);
}

console.log("# opts:", opts);
console.log("# args:", opts._args);

// Use `parser.help()` for formatted options help.
if (opts.help) {
    var help = parser.help({includeEnv: true}).trimRight();
    console.log('usage: node foo.js [OPTIONS]\n'
                + 'options:\n'
                + help);
    process.exit(0);
}

// ...

Some example output from this script (foo.js):

$ node foo.js -h
# opts: { help: true,
  _order: [ { name: 'help', value: true, from: 'argv' } ],
  _args: [] }
# args: []
usage: node foo.js [OPTIONS]
options:
    --version             Print tool version and exit.
    -h, --help            Print this help and exit.
    -v, --verbose         Verbose output. Use multiple times for more verbose.
    -f FILE, --file=FILE  File to process

$ node foo.js -v
# opts: { verbose: [ true ],
  _order: [ { name: 'verbose', value: true, from: 'argv' } ],
  _args: [] }
# args: []

$ node foo.js --version arg1
# opts: { version: true,
  _order: [ { name: 'version', value: true, from: 'argv' } ],
  _args: [ 'arg1' ] }
# args: [ 'arg1' ]

$ node foo.js -f bar.txt
# opts: { file: 'bar.txt',
  _order: [ { name: 'file', value: 'bar.txt', from: 'argv' } ],
  _args: [] }
# args: []

$ node foo.js -vvv --file=blah
# opts: { verbose: [ true, true, true ],
  file: 'blah',
  _order:
   [ { name: 'verbose', value: true, from: 'argv' },
     { name: 'verbose', value: true, from: 'argv' },
     { name: 'verbose', value: true, from: 'argv' },
     { name: 'file', value: 'blah', from: 'argv' } ],
  _args: [] }
# args: []

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:

    {
        names: ['verbose', 'v'],
        type: 'arrayOfBool',
        env: 'FOO_VERBOSE',         // <--- add this line
        help: 'Verbose output. Use multiple times for more verbose.'
    },

then the "FOO_VERBOSE" environment variable can be used to set this option:

$ FOO_VERBOSE=1 node foo.js
# opts: { verbose: [ true ],
  _order: [ { name: 'verbose', value: true, from: 'env' } ],
  _args: [] }
# args: []

Boolean options will interpret the empty string as unset, '0' as false and anything else as true.

$ FOO_VERBOSE= node examples/foo.js                 # not set
# opts: { _order: [], _args: [] }
# args: []

$ FOO_VERBOSE=0 node examples/foo.js                # '0' is false
# opts: { verbose: [ false ],
  _order: [ { key: 'verbose', value: false, from: 'env' } ],
  _args: [] }
# args: []

$ FOO_VERBOSE=1 node examples/foo.js                # true
# opts: { verbose: [ true ],
  _order: [ { key: 'verbose', value: true, from: 'env' } ],
  _args: [] }
# args: []

$ FOO_VERBOSE=boogabooga node examples/foo.js       # true
# opts: { verbose: [ true ],
  _order: [ { key: 'verbose', value: true, from: 'env' } ],
  _args: [] }
# args: []

Non-booleans can be used as well. Strings:

$ FOO_FILE=data.txt node examples/foo.js
# opts: { file: 'data.txt',
  _order: [ { key: 'file', value: 'data.txt', from: 'env' } ],
  _args: [] }
# args: []

Numbers:

$ FOO_TIMEOUT=5000 node examples/foo.js
# opts: { timeout: 5000,
  _order: [ { key: 'timeout', value: 5000, from: 'env' } ],
  _args: [] }
# args: []

$ FOO_TIMEOUT=blarg node examples/foo.js
foo: error: arg for "FOO_TIMEOUT" is not a positive integer: "blarg"

With the includeEnv: true config to parser.help() the environment variable can also be included in help output:

usage: node foo.js [OPTIONS]
options:
    --version             Print tool version and exit.
    -h, --help            Print this help and exit.
    -v, --verbose         Verbose output. Use multiple times for more verbose.
                          Environment: FOO_VERBOSE=1
    -f FILE, --file=FILE  File to process

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:

Dashdash will return bash completion file content given a parser instance:

var parser = dashdash.createParser({options: options});
console.log( parser.bashCompletion({name: 'mycli'}) );

or directly from a options array of options specs:

var code = dashdash.bashCompletionFromOptions({
    name: 'mycli',
    options: OPTIONS
});

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.

Parser config

Parser construction (i.e. dashdash.createParser(CONFIG)) takes the following fields:

Option specs

Example using all fields (required fields are noted):

{
    names: ['file', 'f'],       // Required (one of `names` or `name`).
    type: 'string',             // Required.
    completionType: 'filename',
    env: 'MYTOOL_FILE',
    help: 'Config file to load before running "mytool"',
    helpArg: 'PATH',
    helpWrap: false,
    default: path.resolve(process.env.HOME, '.mytoolrc')
}

Each option spec in the options array must/can have the following fields:

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:

var options = [
    {
        group: 'Armament Options'
    },
    {
        names: [ 'weapon', 'w' ],
        type: 'string'
    },
    {
        group: 'General Options'
    },
    {
        names: [ 'help', 'h' ],
        type: 'bool'
    }
];
...

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:

    Options:
      Armament Options:
    ^^  -w WEAPON, --weapon=WEAPON  Weapon with which to crush. One of: |
   /                                sword, spear, maul                  |
  /   General Options:                                                  |
 /      -h, --help                  Print this help and exit.           |
/   ^^^^                            ^                                   |
\       `-- indent                   `-- helpCol              maxCol ---'
 `-- headingIndent

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:

var dashdash = require('dashdash');
dashdash.addOptionType({
    name: '...',
    takesArg: true,
    helpArg: '...',
    parseArg: function (option, optstr, arg) {
        ...
    },
    array: false,  // optional
    arrayFlatten: false,  // optional
    default: ...,   // optional
    completionType: ...  // optional
});

For example, a simple option type that accepts 'yes', 'y', 'no' or 'n' as a boolean argument would look like:

var dashdash = require('dashdash');

function parseYesNo(option, optstr, arg) {
    var argLower = arg.toLowerCase()
    if (~['yes', 'y'].indexOf(argLower)) {
        return true;
    } else if (~['no', 'n'].indexOf(argLower)) {
        return false;
    } else {
        throw new Error(format(
            'arg for "%s" is not "yes" or "no": "%s"',
            optstr, arg));
    }
}

dashdash.addOptionType({
    name: 'yesno'
    takesArg: true,
    helpArg: '<yes|no>',
    parseArg: parseYesNo
});

var options = {
    {names: ['answer', 'a'], type: 'yesno'}
};
var opts = dashdash.parse({options: options});

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?

License

MIT. See LICENSE.txt.