-
Notifications
You must be signed in to change notification settings - Fork 105
Validation
Command-line-args parses the command line but does not validate what was collected. The example below demonstrates how commandLineArgs
output could be validated (e.g. to verify required options were set).
This example verifies either the --help
option was set or all supplied files exist and a valid --log-level
value was set.
const commandLineArgs = require('command-line-args')
const fs = require('fs')
const optionDefinitions = [
{ name: 'help', alias: 'h', type: Boolean },
{ name: 'files', type: String, multiple: true, defaultOption: true },
{ name: 'log-level', type: String }
]
const options = commandLineArgs(optionDefinitions)
const valid =
options.help ||
(
/* all supplied files should exist and --log-level should be one from the list */
options.files &&
options.files.length &&
options.files.every(fs.existsSync) &&
[ 'info', 'warn', 'error', undefined ].includes(options['log-level'])
)
console.log('Your options are', valid ? 'valid' : 'invalid')
console.log(options)
Example output.
$ node example/validate.js package.json README.md
Your options are valid
{ files: [ 'package.json', 'README.md' ] }
Because this module specialises in one task - finding and extracting values set against defined options in process.argv
. Whether those extracted values meet certain criteria or not is for the consuming application, or separate module to decide. Early versions of the module included simple validation features but they attracted too much conflicting opinion and general issue noise, resulting in reduced module stability. The module author decided the concern of testing whether parsed values meet certain criteria was a separate one and preferred not to maintain it as part of this project.