Skip to content
Myr

options-custom-processing.js

This file

Path

examples/options-custom-processing.js

53 lines · 1.7 KiB · JavaScript

Last changed by

Use standard import in examples (#2168)John Geebefore adoption41b12cf

History of this file

Take it

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

Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d

lines 1–6why, 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.6

Use standard import in examples (#2168)John Geebefore adoption41b12cf

line 7why, one step back
7const commander = require('commander');

Add hooks for life cycle events: using .hook() (#1514)John Geebefore adoptionc20284d

lines 8–53why, one step back
8const program = new commander.Command();
910function myParseInt(value, dummyPrevious) {11 // parseInt takes a string and a radix12 const parsedValue = parseInt(value, 10);13 if (isNaN(parsedValue)) {14 throw new commander.InvalidArgumentError('Not a number.');15 }16 return parsedValue;17}1819function increaseVerbosity(dummyValue, previous) {20 return previous + 1;21}2223function collect(value, previous) {24 return previous.concat([value]);25}2627function commaSeparatedList(value, dummyPrevious) {28 return value.split(',');29}3031program32 .option('-f, --float <number>', 'float argument', parseFloat)33 .option('-i, --integer <number>', 'integer argument', myParseInt)34 .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)35 .option('-c, --collect <value>', 'repeatable value', collect, [])36 .option('-l, --list <items>', 'comma separated list', commaSeparatedList)37;3839program.parse();4041const options = program.opts();42if (options.float !== undefined) console.log(`float: ${options.float}`);43if (options.integer !== undefined) console.log(`integer: ${options.integer}`);44if (options.verbose > 0) console.log(`verbosity: ${options.verbose}`);45if (options.collect.length > 0) console.log(options.collect);46if (options.list !== undefined) console.log(options.list);4748// Try the following:49// node options-custom-processing -f 1e250// node options-custom-processing --integer 251// node options-custom-processing -v -v -v52// node options-custom-processing -c a -c b -c c53// node options-custom-processing --list x,y,z