vpalos.com // milk, cookies, segfaults…

Command-line option parser in JavaScript.

by Valeriu Paloş on May 20, 2011

Here’s a small but very effective command-line option parser written in JavaScript (uses NodeJs). You can get the up-to-date source code at http://gist.github.com/982499.

I wrote this because I needed it for a project and I did not think it was worth it to install some npm package just for this. The comment should explain most things you will need but ask me if you don’t understand something. Note that this code is not well tested (yet!) since I just wrote it this morning so post a comment when you find a bug.

Supports:

  • Short and long options (i.e. ‘-t|--test‘).
  • Option parameters (i.e. ‘-f /etc/resolv.conf‘).
  • Mandatory options.
  • Implicit help option.
  • Option callback functions.
  • Cumulated short options (i.e. ‘-ab‘).
  • Repeatable options (i.e. ‘--add value1 --add value2‘).
  • Non-option arguments.

Notes (extracted from the comments):

  • Parser is case-sensitive.
  • The ‘-h|–help’ option is provided implicitly.
  • Successfully parsed options will be available as fields in the “options” object.
  • Non-option arguments found will be available in order in the “arguments” array.
  • Options and their parameters must be separated by space.
  • Either one of «short» or «long» must always be provided.
  • The «callback» function is optional and is invoked each time the option is encountered.
  • Cumulated short options are supported (i.e. ‘-tv‘).
  • If an error occurs, the process is halted and the help message is shown.
  • Options with the “multiple” attribute will be cumulated into arrays (even if found only once).
  • The parser does *not* test for duplicate definitions in the schema array.

See the code for everything else you need to use it (i.e. a sample schema definition). I will not waste any more time talking about it; if you like it, paste it at the top of your NodeJS script and start playing with it, e.g.:

$ node options.js -tf /some/file.txt foo bar

Also, please tell me about any improvements or fixes you produce. Thanks and… enjoy! :)

Don't keep it to yourself!...