-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
options-custom-processing.js
executable file
·57 lines (47 loc) · 1.72 KB
/
options-custom-processing.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/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');
const program = new commander.Command();
function myParseInt(value) {
// 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) {
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