arguments-custom-processing.js
This file
Path
examples/arguments-custom-processing.js
46 lines · 1.3 KiB · JavaScript
Last changed by
Switching to esm-only (#2464)John Geebefore adoptionf4bd470
History of this fileTake it
The walk stopped after 200 commits: lines older than 471ec40 point at it.
Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40
lines 1–6why, one step back1#!/usr/bin/env node23// 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.6Switching to esm-only (#2464)John Geebefore adoptionf4bd470
lines 7–8why, one step back7import { Command, InvalidArgumentError } from 'commander';8const program = new Command();Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40
line 9why, one step back9ESLint changes preparing for Prettier (#2153)John Geebefore adoption6fc933e
line 10why, one step back10function myParseInt(value) {Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40
lines 11–13why, one step back11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {Switching to esm-only (#2464)John Geebefore adoptionf4bd470
line 14why, one step back14 throw new InvalidArgumentError('Not a number.');Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40
lines 15–46why, one step back15 }16 return parsedValue;17}1819// The previous value passed to the custom processing is used when processing variadic values.20function mySum(value, total) {21 return total + myParseInt(value);22}2324program25 .command('add')26 .argument('<first>', 'integer argument', myParseInt)27 .argument('[second]', 'integer argument', myParseInt, 1000)28 .action((first, second) => {29 console.log(`${first} + ${second} = ${first + second}`);30 });3132program33 .command('sum')34 .argument('<value...>', 'values to be summed', mySum, 0)35 .action((total) => {36 console.log(`sum is ${total}`);37 });3839program.parse();4041// Try the following:42// node arguments-custom-processing add --help43// node arguments-custom-processing add 244// node arguments-custom-processing add 12 5645// node arguments-custom-processing sum 1 2 346// node arguments-custom-processing sum silly