options-custom-processing.js
This file
Path
examples/options-custom-processing.js
54 lines · 1.8 KiB · JavaScript
Last changed by
Extend .argument() to add default value and custom parse for command-argument (#1508)John Geebefore adoptionf99d6fa
History of this fileTake it
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455#!/usr/bin/env node
// This is used as an example in the README for:// Custom option processing// You may specify a function to do custom processing of option values.
// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repoconst program = new commander.Command();
function myParseInt(value, dummyPrevious) { // parseInt takes a string and a radix const parsedValue = parseInt(value, 10); if (isNaN(parsedValue)) { throw new commander.InvalidArgumentError('Not a number.'); } return parsedValue;}
function increaseVerbosity(dummyValue, previous) { return previous + 1;}
function collect(value, previous) { return previous.concat([value]);}
function commaSeparatedList(value, dummyPrevious) { return value.split(',');}
program .option('-f, --float <number>', 'float argument', parseFloat) .option('-i, --integer <number>', 'integer argument', myParseInt) .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0) .option('-c, --collect <value>', 'repeatable value', collect, []) .option('-l, --list <items>', 'comma separated list', commaSeparatedList);
program.parse();
const options = program.opts();if (options.float !== undefined) console.log(`float: ${options.float}`);if (options.integer !== undefined) console.log(`integer: ${options.integer}`);if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);if (options.collect.length > 0) console.log(options.collect);if (options.list !== undefined) console.log(options.list);
// Try the following:// node options-custom-processing -f 1e2// node options-custom-processing --integer 2// node options-custom-processing -v -v -v// node options-custom-processing -c a -c b -c c// node options-custom-processing --list x,y,z