A simple but powerful command line parser for Node.js
A powerful-but-simple command line parser for Node.js apps, inspired by William Morgan's awesome Trollop gem for Ruby.
Troll-opt allows you to define and parse command line args in one simple definition. One line per opt: that's all you need. No chaining long series of commands together, no multiline parsing definitions.
A simple single option defintion looks like this:
optionstopt"word" "something to talk about" default: 'cake';
Or, a slightly more complicated definition that takes three different arguments and defines a help banner:
Troll = require'troll-opt'Trollopts = optionstrollbanner'Web listener that always responds with a defined message';trollopt'errors' 'Issue random errors to some responses' default: true ;trollopt'name' 'The name of the application' type: 'string' required: true ;trollopt'code' 'The normal response code to generate' short: 'o' default: 200 ;;
This in turn will supply the following help document when the calling
application is invoked with the help flag:
Usage: app.js [options]Web listener that always responds with a defined message--code, -o <n>: The normal response code to generate (default: 200)--errors, -e: Issue random errors to some responses (default: false)--name, -n <s>: The name of the application (required)--help: Display this help text
If we pass that a command line like:
$ ./test.js --name="something" --errors --code 201
$ ./test.js --name something --errors --code 201
$ ./test.js -n something -e -o 201
we then get the following contents of
opts as defined above:
name: 'something' errors: true code: 201
Troll-opt will do camelCase conversion of options for you for mulit-word command line arguments.
$ ./test.js --lib-path /usr/lib
Generates the options object:
You assign these in the definition in camelCase and the command line parser does
the translation from
libPath before doing the lookup:
opts = optionstrollopt'libPath' 'Path to the libraries' default: '/usr/lib/' ;
Any arguments that are supplied at the end of the command line, but which are not options to the previous argument are available via the following mechanism.
Given that the following command is issued:
$ ./test.js --lib-path /usr/lib some-extra-argument another-one
You will need to keep the handle on the original
Troll instance. This can then
be used to access the remaining arguments on the command line like so:
troll =trolloptionstrollopt'libPath' 'Path to the libraries' default: '/usr/lib/' ;
troll.argv will then contain:
Troll-opt, like Trollop, gives you a lot of win for not much work. Here are some of the things you get for free: