Skip to content
Myr

options-custom-processing.js

This file

Path

examples/options-custom-processing.js

54 lines · 1.8 KiB · JavaScript

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 6c06528 point at it.

Add getOptionValue and setOptionValue (#1521)John Geebefore adoption6c06528

lines 1–54why, one step back
1#!/usr/bin/env node
23// This is used as an example in the README for:4// Custom option processing5// You may specify a function to do custom processing of option values.67// const commander = require('commander'); // (normal include)8const commander = require('../'); // include commander in git clone of commander repo9const program = new commander.Command();1011function myParseInt(value, dummyPrevious) {12 // parseInt takes a string and a radix13 const parsedValue = parseInt(value, 10);14 if (isNaN(parsedValue)) {15 throw new commander.InvalidArgumentError('Not a number.');16 }17 return parsedValue;18}1920function increaseVerbosity(dummyValue, previous) {21 return previous + 1;22}2324function collect(value, previous) {25 return previous.concat([value]);26}2728function commaSeparatedList(value, dummyPrevious) {29 return value.split(',');30}3132program33 .option('-f, --float <number>', 'float argument', parseFloat)34 .option('-i, --integer <number>', 'integer argument', myParseInt)35 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)36 .option('-c, --collect <value>', 'repeatable value', collect, [])37 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)38;3940program.parse();4142const options = program.opts();43if (options.float !== undefined) console.log(`float: ${options.float}`);44if (options.integer !== undefined) console.log(`integer: ${options.integer}`);45if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);46if (options.collect.length > 0) console.log(options.collect);47if (options.list !== undefined) console.log(options.list);4849// Try the following:50// node options-custom-processing -f 1e251// node options-custom-processing --integer 252// node options-custom-processing -v -v -v53// node options-custom-processing -c a -c b -c c54// node options-custom-processing --list x,y,z