parse-options

1.0.6 • Public • Published

Maintenance Maintaner Website shields.io made-with-Markdown made-for-VSCode GitHub license Profile views GitHub contributors GitHub issues

GitHub forks GitHub stars GitHub watchers GitHub followers

parse-options

Parse Command Line Options

Installation

npm install parse-options;

or

yarn add parse-options;

Example

Command:

node app.js copy -m --lim 5 --exclude 'node_modules' test.txt

app.js:

const parseOptions = require('parse-options');

let options = parseOptions(
  // Example pattern.
  // Contains two commands (command="copy", file="test.txt")
  // and three parameters (boolean minimize=true, number limit=5
  // and string exclude="node_modules")
  `command file @minimize|min|m #limit|lim|l $exclude|e`,
  // Command line arguments
  process.argv,
  // Handlers applied after parsing
  {
    file => path.resolve(process.env, file),
  }
);

options === {
  // Commands list
  $commands: ['copy', 'test.txt'],
  // Named commands values
  command: 'copy',
  file: 'test.txt',
  // Named parameters
  minimize: true,
  limit: 5,
  exclude: 'node_modules',
};

Using

const parseOptions = require('parse-options');

let options = parseOptions([pattern], [argv]);

Pattern

Pattern is a template string, defining options names and types. Pattern can contain commands list (values, defined by position) and named parameters with types.

You can omit pattern by specifying null as first argument. This will parse all arguments as strings or booleans by default.

Parameters

To define simple string named parameter (for example, for parsing --file 'test.txt'), specify the following pattern:

$file|f

That pattern defines argument named file, which is parsing from argv parameter --file VALUE, -f VALUE, --file=VALUE, or -f=VALUE.

Boolean and number parameters is defining the same way:

@minimize|min|m #age|a

The code above defines two parameters: boolean minimize with aliases minimize, min and m, and age with aliases age and a.

Commands

Command is a string value, gived as a positioned argument to the CLI. For, example, the following code contains two command values: copy and test.txt:

node app.js copy -a text.txt;

Commands can be specified in any order. For example, the code above will be parsed with pattern action filename @all|a as

{
  $commands: ['copy', 'text.txt'],
  action: 'copy',
  filename: 'text.txt',
  all: true,
}

Other Example

Pattern:

from to @recursive|r $exclude|e;

Command Line:

node app.js ./source/ ./dest/ --exclude 'node_modules';

Result:

{
  $commands: ['./source/', './dest/'],
  from: './source/',
  to: './dest/',
  recursive: false,
  exclude: 'node_modules',
}

Package Sidebar

Install

npm i parse-options

Weekly Downloads

24

Version

1.0.6

License

MIT

Unpacked Size

18.1 kB

Total Files

14

Last publish

Collaborators

  • teniryte