Skip to content
Myr

arguments-custom-processing.js

This file

Path

examples/arguments-custom-processing.js

47 lines · 1.4 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–47why, one step back
1#!/usr/bin/env node
23// This is used as an example in the README for:4// Custom argument processing5// You may specify a function to do custom processing of argument 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}1920// The previous value passed to the custom processing is used when processing variadic values.21function mySum(value, total) {22 return total + myParseInt(value);23}2425program26 .command('add')27 .argument('<first>', 'integer argument', myParseInt)28 .argument('[second]', 'integer argument', myParseInt, 1000)29 .action((first, second) => {30 console.log(`${first} + ${second} = ${first + second}`);31 });3233program34 .command('sum')35 .argument('<value...>', 'values to be summed', mySum, 0)36 .action((total) => {37 console.log(`sum is ${total}`);38 });3940program.parse();4142// Try the following:43// node arguments-custom-processing add --help44// node arguments-custom-processing add 245// node arguments-custom-processing add 12 5646// node arguments-custom-processing sum 1 2 347// node arguments-custom-processing sum silly