npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

raptor-args

v1.0.3

Published

A concise command line arguments parser with robust type handling

Downloads

75,755

Readme

raptor-args

A flexible and simple command line arguments parser that generates friendly help messages.

Installation

npm install raptor-args --save

Usage

// Create a parser:
var parser = require('raptor-args').createParser(options);
var parsed = parser.parse(argsArray);

// parsed will be an object with properties corresponding to provided arguments

Simple Example

Parse arguments provided by process.argv:

Given the following JavaScript code to parse the args:

// Create a parser and parse process.argv
require('raptor-args').createParser({
        '--foo -f': 'boolean',
        '--bar -b': 'string'
    })
    .parse();

And the following command:

node app.js --foo -b b

The output will be:

//Output:
{
    foo: true,
    bar: 'baz'
}

You can also parse your own array of arguments instead of using process.argv:

// Create a parser and parse provided args
require('raptor-args').createParser({
        '--foo -f': 'boolean',
        '--bar -b': 'string'
    })
    .parse(['--foo', '-b', 'baz']);

//Output:
{
    foo: true,
    bar: 'baz'
}

You can also be more descriptive and add usage, examples, error handlers and validation checks:

// Create a parser:
require('raptor-args')
    .createParser({
        '--help': {
            type: 'string',
            description: 'Show this help message'
        },
        '--foo -f': {
            type: 'string',
            description: 'Some helpful description for "foo"'
        },
        '--bar -b': {
            type: 'string',
            description: 'Some helpful description for "bar"'
        }
    })
    .usage('Usage: $0 [options]')
    .example(
        'First example',
        '$0 --foo hello')
    .example(
        'Second example',
        '$0 --foo hello --bar world')
    .validate(function(result) {
        if (result.help) {
            this.printUsage();
            process.exit(0);
        }

        if (!result.foo || !result.bar) {
            this.printUsage();
            console.log('--foo or --bar is required');
            process.exit(1);
        }
    })
    .onError(function(err) {
        this.printUsage();
        console.error(err);
        process.exit(1);
    })
    .parse();

Running the above program with the --help argument will produce the following output:

Usage: args [options]

Examples:

  First example:
     args --foo hello

  Second example:
     args --foo hello --bar world

Options:

  --help Show this help message [string]

--foo -f Some helpful description for "foo" [string]

--bar -b Some helpful description for "bar" [string]

Aliases

Aliases can be provided as space-separated values for an option:

// Create a parser:
var parser = require('raptor-args').createParser({
    '--foobar --foo -f': 'string', // "--foobar" has two aliases: "--foo" and "-f"
    '--hello -h': 'string',        // "--hello" has one alias: "-h"
});

parser.parse('--foo FOO -h HELLO'.split(' '));
// Output:
{
    foobar: 'FOO',
    hello: 'HELLO'
}

// **NOTE**: Only the first entry is used to determine the target property name--not the aliases.

Booleans

An argument value of "true" or "false" is automatically converted to the corresponding boolean type. If a argument is prefixed with "no-" then it will be set to false.

// Create a parser:
var parser = require('raptor-args').createParser({
    '--foo': 'boolean',
    '--bar': 'boolean'
});

parser.parse('--foo --no-bar'.split(' '));
// Output:
{
    foo: true,
    bar: false
}

Arrays

Any argument with multiple values will result in an Array value, but if you want to force an array for a single value then you can append "[]" to the option type as shown in the following sample code:

// Create a parser:
var parser = require('raptor-args').createParser({
    '--foo': 'string[]'
});

parser.parse('--foo a'.split(' '));
// Output:
{
    foo: ['a']
}

parser.parse('--foo a b c'.split(' '));
// Output:
{
    foo: ['a', 'b', 'c']
}

Wildcards

A parser will throw an error for unrecognized arguments unless wildcards are used as shown in the examples below.

// Create a parser:
var parser = require('raptor-args').createParser({
    '--foo -f *': 'string[]' // Any unrecognized argument at the beginning is an alias for "foo"
});

parser.parse('a b --foo c'.split(' '));
// Output:
{
    foo: ['a', 'b', 'c']
}
// Create a parser:
var parser = require('raptor-args').createParser({
    '*': null
});

parser.parse('a b --foo FOO --bar BAR'.split(' '));
// Output:
{
    '*': ['a', 'b'],
    foo: 'FOO',
    bar: 'BAR'
}

Complex Types

Square brackets can be used to begin and end complex types:

// Create a parser:
var parser = require('raptor-args').createParser({
    '--foo -f': 'boolean',
    '--plugins --plugin -p': {
        options: {
            '--module -m *': 'string',
            '-*': null
        }
    }
});

var parsed = parser.parse('--foo --plugins [ --module plugin1 -x -y ] [ plugin2 -z Hello ]'.split(' '));

// Output:
{
    foo: true,
    plugins: [
        {
            module: 'plugin1',
            x: true,
            y: true
        },
        {
            module: 'plugin2',
            z: 'Hello'
        }
    ]
}

Similar Projects

  • optimist - Popular but deprecated. Awkward API and not DRY as shown in the following comparison:

optimist:

var result = require('optimist')(args)
    .alias('h', 'help')
    .describe('h', 'Show this help message')
    .boolean('h')
    .alias('f', 'foo')
    .describe('f', 'Some helpful description for "foo"')
    .string('f')
    .alias('b', 'bar')
    .describe('b', 'Some helpful description for "bar"')
    .string('b')
    .argv;

raptor-args:

var result = require('raptor-args')
    .createParser({
        '--help':   { type: 'string', description: 'Show this help message' },
        '--foo -f': { type: 'string', description: 'Some helpful description for "foo"' },
        '--bar -b': { type: 'string', description: 'Some helpful description for "bar"' }
    })
    .parse();
  • yargs - A fork of optimist with documentation for those who speak Pirate.
  • minimist - Very few features (by design). Not DRY.

TODO

  • Support equal separator: --hello=world
  • Support number arg: -x256
  • Detect repeated declared options and throw an error
  • Add support for a default value
var parser = require('../')
    .createParser({
        '--foo -f': {
            type: 'boolean',
            defaultValue: true
        }
    });

Additional Reading

For module help, check out the test cases under the "test" directory.

License

MIT