commit 08dc0ecfe1ed4516f9a5ab128be4678f5bc100f9
Author: James Halliday
Date: Wed Dec 1 07:58:59 2010 +0000

Optimist is an option parser I wrote for node.js that generates a hash from process.argv and gets out of your way. You don't need to define any optstrings or option data structures, just do:

#!/usr/bin/env node
var argv = require('optimist').argv;
console.dir(argv);

$ ./opts.js --foo bar -xzf moo.tar somedir/
{ _: [ 'somedir/' ]
, '$0': 'node ./opts.js'
, foo: 'bar'
, x: true
, z: true
, f: 'moo.tar'
}

So easy! You can do long options, short options, grouped options, --key value or --key=value, and even non-hyphenated options, which end up in argv._. It all ends up in argv.

But that's not all! You can tack on extra goodies pipeline-style between the require('optimist') and the .argv like this:

var argv = require('optimist')
    .usage('Usage: $0 -x [num] -y [num]')
    .demand(['x','y'])
    .argv
;
console.log(argv.x / argv.y);

which complains at you if you don't pass in -x and -y:

$ ./divide.js -x 4.91 -z 2.51
Usage: ./divide.js -x [num] -y [num]
Missing arguments: y

but otherwise just gives you back a plain ol' hash and just works™.

$ ./divide.js -x 55 -y 11
5

Check out the code on github for more examples and features. I like pull requests!

more
git clone http://substack.net/blog.git