Skip to content
Lloyd Brookes edited this page Jan 23, 2018 · 4 revisions

Command-line-args parses the command line but does not validate what was collected. This example demonstrates how those values could be validated.

Validation Example

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' ] }

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 values meet certain criteria was a separate one and preferred not to maintain it as part of this project.