$ cnpm install argv
argv is a nodejs module that does command line argument parsing.
$ npm install argv
var argv = require( 'argv' );
var args = argv.option( options ).run();
-> { targets: [], options: {} }
Runs the argument parser on the global arguments. Custom arguments array can be used by passing into this method
// Parses default arguments 'process.argv.slice( 2 )'
argv.run();
// Parses array instead
argv.run([ '--option=123', '-o', '123' ]);
argv is a strict argument parser, which means all options must be defined before parsing starts.
argv.option({
name: 'option',
short: 'o',
type: 'string',
description: 'Defines an option for your script',
example: "'script --opiton=value' or 'script -o value'"
});
Modules are nested commands for more complicated scripts. Each module has it's own set of options that have to be defined independently of the root options.
argv.mod({
mod: 'module',
description: 'Description of what the module is used for',
options: [ list of options ]
});
Types convert option values to useful js objects. They are defined along with each option.
argv.option([
{
name: 'option',
type: 'csv,int'
},
{
name: 'path',
short: 'p',
type: 'list,path'
}
]);
// csv and int combo
$ script --option=123,456.001,789.01
-> option: [ 123, 456, 789 ]
// list and path combo
$ script -p /path/to/file1 -p /path/to/file2
-> option: [ '/path/to/file1', '/path/to/file2' ]
You can also create your own custom type for special conversions.
argv.type( 'squared', function( value ) {
value = parseFloat( value );
return value * value;
});
argv.option({
name: 'square',
short: 's',
type: 'squared'
});
$ script -s 2
-> 4
Defining the scripts version number will add the version option and print it out when asked.
argv.version( 'v1.0' );
$ script --version
v1.0
Custom information can be displayed at the top of the help printout using this method
argv.info( 'Special script info' );
$ script --help
Special script info
... Rest of Help Doc ...
If you have competing scripts accessing the argv object, you can clear out any previous options that may have been set.
argv.clear().option( [new options] );
argv injects a default help option initially and on clears. The help() method triggers the help printout.
argv.help();
Copyright 2013 - present © cnpmjs.org