You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Lloyd Brookes edited this page Nov 13, 2019
·
4 revisions
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).
Validation Example
This example verifies either the --help option was set or all supplied files exist and a valid --log-level value was set.
constcommandLineArgs=require('command-line-args')constfs=require('fs')constoptionDefinitions=[{name: 'help',alias: 'h',type: Boolean},{name: 'files',type: String,multiple: true,defaultOption: true},{name: 'log-level',type: String}]constoptions=commandLineArgs(optionDefinitions)constvalid=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' ] }
Why is validation not built into the module?
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.