Skip to content

Typical usage example

Lloyd Brookes edited this page Sep 22, 2019 · 7 revisions

This example shows typical use alongside command-line-usage.

First, install the packages.

$ npm install command-line-args command-line-usage

Example source code. The description and typeLabel properties in the optionDefinitions are consumed by command-line-usage only, not command-line-args.

const commandLineArgs = require('command-line-args')
const commandLineUsage = require('command-line-usage')

const optionDefinitions = [
  {
    name: 'help',
    alias: 'h',
    type: Boolean,
    description: 'Display this usage guide.'
  },
  {
    name: 'src',
    type: String,
    multiple: true,
    description: 'The input files to process',
    typeLabel: '<files>' },
  {
    name: 'timeout',
    alias: 't',
    type: Number,
    description: 'Timeout value in ms',
    typeLabel: '<ms>' },
  {
    name: 'log',
    alias: 'l',
    type: String,
    description: 'info, warn or error'
  }
]

const options = commandLineArgs(optionDefinitions)

if (options.help) {
  const usage = commandLineUsage([
    {
      header: 'Typical Example',
      content: 'A simple example demonstrating typical usage.'
    },
    {
      header: 'Options',
      optionList: optionDefinitions
    },
    {
      content: 'Project home: {underline https://github.com/me/example}'
    }
  ])
  console.log(usage)
} else {
  console.log(options)
}

Example invocation.

$ node typical.js --help

Typical Example

  A simple example demonstrating typical usage.

Options

  -h, --help           Display this usage guide.
  --src <files>        The input files to process
  -t, --timeout <ms>   Timeout value in ms
  -l, --log            info, warn or error

  Project home: https://github.com/me/example

Another example invocation.

$ node typical.js --src * -l info -t 100
{ src:
   [ 'LICENSE',
     'README.md',
     'index.js',
     'lib',
     'package-lock.json',
     'package.json',
     'test' ],
  log: 'info',
  timeout: 100 }