RingoJS

Module ringo/args

A parser for command line options. This parser supports various option formats:

  • -a -b -c (multiple short options)
  • -abc (multiple short options combined into one)
  • -a value (short option with value)
  • -avalue (alternative short option with value)
  • --option value (long option with value)
  • --option=value (alternative long option with value)

Example

// ringo parserExample.js -v --size 123 -p 45678

const term = require('ringo/term');
const system = require('system');
const {Parser} = require('ringo/args');

const parser = new Parser();
parser.addOption('s', 'size', 'SIZE', 'Sets the size to SIZE');
parser.addOption('p', 'pid', 'PID', 'Kill the process with the PID');
parser.addOption('v', 'verbose', null, 'Verbosely do something');
parser.addOption('h', 'help', null, 'Show help');

const options = parser.parse(system.args.slice(1));
if (options.help) {
  term.writeln(parser.help());
} else {
  if (options.size) {
     term.writeln('Set size to ' + parseInt(options.size));
  }

  if (options.pid) {
     term.writeln('Kill process ' + options.pid);
  }

  if (options.verbose) {
     term.writeln('Verbose!');
  }
}

if (!Object.keys(options).length) {
  term.writeln("Run with -h/--help to see available options");
}

Class Parser

Instance Methods


Parser ()

Create a new command line option parser.


Parser.prototype. addOption (shortName, longName, argument, helpText)

Add an option to the parser.

Parameters

String shortName

the short option name (without leading hyphen)

String longName

the long option name (without leading hyphens)

String argument

display name of the option's value, or null if the argument is a singular switch

String helpText

the help text to display for the option

Returns

Object

this parser for chained invocation


Parser.prototype. help ()

Get help text for the parser's options suitable for display in command line scripts.

Returns

String

a string explaining the parser's options


Parser.prototype. parse (args, result)

Parse an arguments array into an option object. If a long option name is defined, it is converted to camel-case and used as property name. Otherwise, the short option name is used as property name.

Passing an result object as second argument is a convenient way to define default options:

Example

parser.parse(system.args.slice(1), {myOption: "defaultValue"});

Parameters

Array args

the argument array. Matching options are removed.

Object result

optional result object. If undefined, a new Object is created.

Returns

Object

the result object