UNPKG

996 BJavaScriptView Raw
1/*
2 command-line-args parses the command line but does not validate what was collected.
3 This example demonstrates how the values collected can be validated.
4*/
5
6'use strict'
7const commandLineArgs = require('../')
8const fs = require('fs')
9
10const optionDefinitions = [
11 { name: 'help', alias: 'h', type: Boolean },
12 { name: 'files', type: String, multiple: true, defaultOption: true },
13 { name: 'log-level', type: String }
14]
15
16const options = commandLineArgs(optionDefinitions)
17
18const valid =
19 options.help ||
20 (
21 /* all supplied files should exist and --log-level should be one from the list */
22 options.files &&
23 options.files.length &&
24 options.files.every(fs.existsSync) &&
25 [ 'info', 'warn', 'error', undefined ].includes(options['log-level'])
26 )
27
28console.log('Your options are', valid ? 'valid' : 'invalid')
29console.log(options)
30
31/*
32Example output:
33
34$ node example/validate.js package.json README.md
35Your options are valid
36{ files: [ 'package.json', 'README.md' ] }
37*/