options-conflicts.js
This file
Path
examples/options-conflicts.js
70 lines · 2.5 KiB · JavaScript
Last changed by
Use standard import in examples (#2168)John Geebefore adoption41b12cf
History of this fileTake it
Add extended conflicts example (#1700)John Geebefore adoption1d27078
line 1why, one step back1#!/usr/bin/env nodeUse standard import in examples (#2168)John Geebefore adoption41b12cf
line 2why, one step back2const { Command, Option } = require('commander');Add extended conflicts example (#1700)John Geebefore adoption1d27078
lines 3–70why, one step back3const program = new Command();45// You can use .conflicts() with a single string, which is the camel-case name of the conflicting option.6program7 .command('pay')8 .addOption(new Option('--cash').conflicts('creditCard'))9 .addOption(new Option('--credit-card'))10 .action((options) => {11 if (options.cash) {12 console.log('Paying by cash')13 } else if (options.creditCard) {14 console.log('Paying by credit card')15 } else {16 console.log('Payment method unknown')17 }18 });1920 // The default value for an option does not cause a conflict.21 // A value specified using an environment variable is checked for conflicts.22program23 .command('source')24 .addOption(new Option('-p, --port <number>', 'port number for server')25 .default(80)26 .env('PORT')27 ).addOption(new Option('--interactive', 'prompt for user input instead of listening to a port')28 .conflicts('port')29 ).action((options) => {30 if (options.interactive) {31 console.log('What do you want to do today?')32 } else {33 console.log(`Running server on port: ${options.port}`);34 }35 });3637// You can use .conflicts() with an array of option names.38// A negated option is not separate from the positive option for conflicts (they have same option name).39program40 .command('paint')41 .addOption(new Option('--summer', 'use a mixture of summer colors').conflicts(['autumn', 'colour']))42 .addOption(new Option('--autumn', 'use a mixture of autumn colors').conflicts(['summer', 'colour']))43 .addOption(new Option('--colour <shade>', 'use a single solid colour'))44 .addOption(new Option('--no-colour', 'leave surface natural'))45 .action((options) => {46 let colour = 'not specified';47 if (options.colour === false) {48 colour = 'natural';49 } else if (options.colour) {50 colour = options.colour;51 } else if (options.summer) {52 colour = 'summer';53 } else if (options.autumn) {54 colour = 'autumn';55 }56 console.log(`Painting colour is ${colour}`);57 });5859program.parse();6061// Try the following:62// node options-conflicts.js pay --cash --credit-card63//64// node options-conflicts.js source65// node options-conflicts.js source --interactive66// node options-conflicts.js source --port 8080 --interactive67// PORT=8080 node options-conflicts.js source --interactive68//69// node options-conflicts.js paint --colour=red --summer70// node options-conflicts.js paint --no-colour --autumn