|
| 1 | +// This is an example of adding support for an option with an optional value, |
| 2 | +// which can be used like a boolean-type or a string-type. |
| 3 | + |
| 4 | +import { parseArgs } from 'node:util'; |
| 5 | +import process from 'node:process'; |
| 6 | + |
| 7 | +const options = { |
| 8 | + 'host': { |
| 9 | + type: 'string', |
| 10 | + short: 'h', |
| 11 | + default: 'default.com', |
| 12 | + preset: 'localhost' |
| 13 | + }, |
| 14 | + 'debug': { type: 'boolean', short: 'd' }, |
| 15 | +}; |
| 16 | + |
| 17 | +const args = process.argv.slice(2); |
| 18 | + |
| 19 | +do { |
| 20 | + const { tokens } = parseArgs({ args, options, strict: false, tokens: true }); |
| 21 | + // Insert preset if: |
| 22 | + // - missing value, like: --host |
| 23 | + // - value came from following option argument, like: --host --debug |
| 24 | + // An empty string is a valid value for a string-type option. |
| 25 | + const needsPreset = tokens.find((token) => |
| 26 | + token.kind === 'option' && |
| 27 | + options[token.name] && |
| 28 | + options[token.name].type === 'string' && |
| 29 | + options[token.name].preset !== undefined && |
| 30 | + ( |
| 31 | + token.value === undefined || |
| 32 | + (token.value.startsWith('-') && !token.inlineValue) |
| 33 | + )); |
| 34 | + |
| 35 | + if (!needsPreset) break; |
| 36 | + |
| 37 | + // Add preset value as an inline value to the original argument. |
| 38 | + const joiner = args[needsPreset.index].startsWith('--') ? '=' : ''; |
| 39 | + args[needsPreset.index] = `${args[needsPreset.index]}${joiner}${options[needsPreset.name].preset}`; |
| 40 | + |
| 41 | +} while (true); |
| 42 | + |
| 43 | + |
| 44 | +const { values } = parseArgs({ args, options }); |
| 45 | +console.log(values); |
| 46 | + |
| 47 | +// Try the following: |
| 48 | +// node optional-value.mjs |
| 49 | +// node optional-value.mjs -h |
| 50 | +// node optional-value.mjs --host |
| 51 | +// node optional-value.mjs -hHOSTNAME |
| 52 | +// node optional-value.mjs --host=HOSTNAME |
| 53 | +// node optional-value.mjs --host= |
| 54 | +// node optional-value.mjs -h -d |
| 55 | +// node optional-value.mjs -dh |
| 56 | +// node optional-value.mjs --host --debug |
| 57 | +// node optional-value.mjs --host -- POSITIONAL |
0 commit comments