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

cli-program

v2.0.38

Published

The complete solution for node.js command-line interfaces.

Downloads

13

Readme

cli-program

The complete solution for node.js command-line interfaces.

NPM Version NPM Downloads

Installation

$ npm install cli-program --save

Content

.name(name)

Program name is declared with the .name(name: string) method, also serving as documentation for the program name. The program name can be declared anything or skipped. As default value program uses name of executable filename.

require("cli-program")
    .name("My Awesome Program")
    .parse(function () {
        // bootstrap
    });
$ program --help
My Awesome Program

Usage:

  program

.description(description)

Program description is declared with the .description(description: string) method, also serving as documentation for the program description. The program description can be declared anything or skipped.

require("cli-program")
    .name("My Awesome Program")
    .description("Multi-line detailed description")
    .parse(function () {
        // bootstrap
    });
$ program --help
My Awesome Program

  Multi-line detailed description

Usage:

  program

.usage(usage)

Usage format is declared with the .usage(usage: string) method, also serving as documentation for the usage format. The usage format can be declared anything or skipped. As default value program automatically generates usage by program declaration.

require("cli-program")
    .usage("[options...]")
    .parse(function () {
        // bootstrap
    });
$ program --help
program

Usage:

  program [options...]

.option(flags)

Options are defined with the .option(flags: string, description?: string, defaultValue?: any, negativePrefixes?: string[], preparationFunction?: (value: any) => any) method, also serving as documentation for the options. The example below parses args and options from process.argv.

require("cli-program")
    .version("0.1.0")
    .option("-p, --peppers", "Add peppers")
    .option("-P, --pineapple", "Add pineapple")
    .option("-b, --bbq-sauce", "Add bbq sauce")
    .option("-c, --cheese [type]", "Add the specified type of cheese [marble]", "marble")
    .parse(function (args, opts) {
        console.log("you ordered a pizza with:");
        if (opts.peppers) {
            console.log("  - peppers");
        }
        if (opts.pineapple) {
            console.log("  - pineapple");
        }
        if (opts.bbqSauce) {
            console.log("  - bbq");
        }
        console.log("  - %s cheese", opts.cheese);
    });

Short flags may be passed as a single arg, for example -abc is equivalent to -a -b -c. Multi-word options such as "--template-engine" are camel-cased, becoming opts.templateEngine etc.

Note that multi-word options starting with --no prefix negate the boolean value of the following word. For example, --no-sauce sets the value of args.sauce to false.

require("cli-program")
    .version("0.1.0")
    .option("-p, --password <string>", "Password to connect", null, ["no", "without"])
    .parse(function (args, opts) {
        if (opts.password === false) {
            console.log("Without password!");
        } else {
            console.log("Password: %s", opts.password);
        }
    });

.version(version)

Calling the version implicitly adds the -V and --version options to the program. When either of these options is present, the command prints the version number and exits.

$ ./examples/pizza -V
0.0.1

If you want your program to respond to the -v option instead of the -V option, simply pass custom flags to the version method using the same syntax as the option method:

require("cli-program")
    .version("0.0.1", "-v, --version");

or with special description:

require("cli-program")
    .version("0.0.1", "-v, --version", "Special description");

The version flags can be named anything.

.arguments(arguments)

Arguments are declared with the .arguments(args: string) method. The example below parses args and options from process.argv.

// declare optional argument
require("cli-program").arguments("[optional]");

// declare optional arguments
require("cli-program").arguments("[spread...]");

// declare required argument
require("cli-program").arguments("<required>");

// combination declare
require("cli-program").arguments("<argument1> <argument2> [more...]");

Arguments declaration format

The arguments can be named anything. Angled brackets (e.g. <required>) indicate required input. Square brackets (e.g. [optional]) indicate optional input.

require("cli-program")
    .arguments("<arg1> [args...]")
    .parse(function (args) {
        console.log("args: %s", JSON.stringify(args));
    });
// $ node path/to/program value1 value2 value3
// args: {"arg1":"value1","args":["value2","value3"]}
require("cli-program")
    .arguments("<arg1> [arg2]")
    .parse(function (args) {
        console.log("args: %s", JSON.stringify(args));
    });
// $ node path/to/program value1
// args: {"arg1":"value1","arg2":null}
// $ node path/to/program value1 value2
// args: {"arg1":"value1","arg2":"value2"}

.command(command)

Command declaration format

Command-specific method .action(action)

You can attach handler to a command.

require("cli-program")
    .command("rm <dir>") // comand with required argument
    .action(function (args, opts) {
        console.log("remove " + args.dir + (opts.recursive ? " recursively" : ""))
    })
    .parse()

Command-specific method .options(flags)

You can attach options to a command.

require("cli-program")
    .command("rm <dir>") // comand with required argument
    .option("-r, --recursive", "Remove recursively")
    .action(function (args, opts) {
        console.log("remove " + args.dir + (opts.recursive ? " recursively" : ""))
    })
    .parse()

A command's options are validated when the command is used. Any unknown options will be reported as an error.

Command-specific method .description(description)

You can attach description to a command.

require("cli-program")
    .command("rm <dir>") // comand with required argument
    .description("Remove directory")
    .action(function (args, opts) {
        console.log("remove " + args.dir + (opts.recursive ? " recursively" : ""))
    })
    .parse()

Command-specific method .alias(alias)

You can attach alias to a command.

require("cli-program")
    .command("remove <dir>") // comand with required argument
    .alias("rm")
    .action(function (args, opts) {
        console.log("remove " + args.dir + (opts.recursive ? " recursively" : ""))
    })
    .parse()

Command-specific method .usage(usage)

You can attach usage to a command.

require("cli-program")
    .command("remove <dir>") // comand with required argument
    .usage("...special usage format...")
    .action(function (args, opts) {
        console.log("remove " + args.dir + (opts.recursive ? " recursively" : ""))
    })
    .parse()

Git-style sub-commands

var program = require("cli-program");
program
  .version("0.1.0")
  .command("install [name]", "Install one or more packages")
  .action(function (args, opts) {
    console.log("args: " + JSON.stringify(args));
    console.log("opts: " + JSON.stringify(opts));
  });
program
  .command("search [query]", "Search with optional query")
  .action(function (args, opts) {
    console.log("args: " + JSON.stringify(args));
    console.log("opts: " + JSON.stringify(opts));
  });
program
  .command("list", "List packages installed")
  .action(function (args, opts) {
    console.log("args: " + JSON.stringify(args));
    console.log("opts: " + JSON.stringify(opts));
  });
program.parse();

When .command() is invoked with a description argument, no .action(callback) should be called to handle sub-commands, otherwise there will be an error. This tells commander that you"re going to use separate executables for sub-commands, much like git(1) and other popular tools. The commander will try to search the executables in the directory of the entry script (like ./examples/pm) with the name program-command, like pm-install, pm-search.

Options can be passed with the call to .command(). Specifying true for opts.noHelp will remove the option from the generated help output. Specifying true for opts.isDefault will run the subcommand if no other subcommand is specified.

If the program is designed to be installed globally, make sure the executables have proper modes, like 755.

Automated --help

The help information is auto-generated based on the information commander already knows about your program, so the following --help info is for free:

$ ./examples/pizza --help
pizza

Usage:

  pizza [options...]

Options:

  -h, --help                   Show help
  --no-color,
  --color [value=null]         Disable/enable output colors
  -V, --version                Show version.
  -p, --peppers                Add peppers
  -P, --pineapple              Add pineapple
  -b, --bbq-sauce              Add bbq sauce
  -c, --cheese [type="marble"] Add the specified type of cheese [marble]

Automated --version

The version information is auto-generated based on the information declared via .version(version) method. This case shouldn't have any handlers and works automatically. But version should be declared for work.

$ ./examples/pizza -V
Version: 0.0.1
$ ./examples/pizza --version
Version: 0.0.1

Examples

arguments1.js

"use strict";
require("cli-program")
    // Program have 1 required argument
    // and 1 optional argument.
    .arguments("<arg1> [arg2]")
    .parse(function (args) {
        console.log("args: %s", JSON.stringify(args));
    });

/**
 * $ node ./examples/arguments1.js --help
 * arguments1
 *
 * Usage:
 *
 *   arguments1 [options...] <arg1> [arg2]
 *
 * Options:
 *
 *   -h, --help           Show help
 *   --no-color,
 *   --color [value=null] Disable/enable output colors
 */

/**
 * $ node ./examples/arguments1.js
 * Error: Invalid number of arguments.
 */

/**
 * $ node ./examples/arguments1.js value1
 * args: {"arg1":"value1","arg2":null}
 */

/**
 * $ node ./examples/arguments1.js value1 value2
 * args: {"arg1":"value1","arg2":"value2"}
 */

arguments2.js

"use strict";
require("cli-program")
    // Program have 1 required argument
    // and more optional arguments.
    .arguments("<arg1> [args...]")
    .parse(function (args) {
        console.log("args: %s", JSON.stringify(args));
    });

/**
 * $ node ./examples/arguments2.js --help
 * arguments2
 *
 * Usage:
 *
 *   arguments2 [options...] <arg1> [args...]
 *
 * Options:
 *
 *   -h, --help           Show help
 *   --no-color,
 *   --color [value=null] Disable/enable output colors
 */

/**
 * $ node ./examples/arguments1.js
 * Error: Invalid number of arguments.
 */

/**
 * $ node ./examples/arguments1.js value1
 * args: {"arg1":"value1","args":[]}
 */

/**
 * $ node ./examples/arguments1.js value1 value2
 * args: {"arg1":"value1","args":["value2"]}
 */

/**
 * $ node ./examples/arguments1.js value1 value2 value3
 * args: {"arg1":"value1","args":["value2","value3"]}
 */

commands1.js

"use strict";
var program = require("cli-program");
program
    .command("command1 <required>")
    .alias("cmd1")
    .description("Command with one required argument")
    .option("-O, --option", "Command-specific option")
    .action(function (args, opts) {
        console.log("args: %s", JSON.stringify(args));
        console.log("opts: %s", JSON.stringify(opts));
    });
program
    .command("command2 [optional]")
    .alias("cmd2")
    .description("Command with one optional argument")
    .option("-O, --option", "Command-specific option")
    .action(function (args, opts) {
        console.log("args: %s", JSON.stringify(args));
        console.log("opts: %s", JSON.stringify(opts));
    });
program
    .command("command3 [spread...]")
    .alias("cmd3")
    .description("Command with more optional arguments")
    .option("-O, --option", "Command-specific option")
    .action(function (args, opts) {
        console.log("args: %s", JSON.stringify(args));
        console.log("opts: %s", JSON.stringify(opts));
    });
program
    .command("command4 <argument> [more...]")
    .alias("cmd4")
    .description("Command with combined arguments")
    .option("-O, --option", "Command-specific option")
    .action(function (args, opts) {
        console.log("args: %s", JSON.stringify(args));
        console.log("opts: %s", JSON.stringify(opts));
    });
program.parse();

/**
 * $ node ./examples/commands1.js --help
 * commands1
 *
 * Usage:
 *
 *   commands1 [options...] <command> [arguments...] [options...]
 *
 * Options:
 *
 *   -h, --help           Show help
 *   --no-color,
 *   --color [value=null] Disable/enable output colors
 *
 * Commands:
 *
 *   command1 (alias: cmd1) <required>
 *     Command with one required argument
 *
 *   command2 (alias: cmd2) [optional]
 *     Command with one optional argument
 *
 *   command3 (alias: cmd3) [spread...]
 *     Command with more optional arguments
 *
 *   command4 (alias: cmd4) <argument> [more...]
 *     Command with combined arguments
 */

pizza.js

"use strict";
require("cli-program")
    .name("pizza")
    .version("0.0.1")
    .option("-p, --peppers", "Add peppers")
    .option("-P, --pineapple", "Add pineapple")
    .option("-b, --bbq-sauce", "Add bbq sauce")
    .option("-c, --cheese [type]", "Add the specified type of cheese [marble]", "marble")
    .parse(function (args, opts) {
        console.log("you ordered a pizza with:");
        if (opts.peppers) {
            console.log("  - peppers");
        }
        if (opts.pineapple) {
            console.log("  - pineapple");
        }
        if (opts.bbqSauce) {
            console.log("  - bbq");
        }
        console.log("  - %s cheese", opts.cheese);
    });

/**
 * $ node ./examples/pizza.js --help
 * pizza
 *
 * Usage:
 *
 *   pizza [options...]
 *
 * Options:
 *
 *   -h, --help                   Show help
 *   --no-color,
 *   --color [value=null]         Disable/enable output colors
 *   -V, --version                Show version.
 *   -p, --peppers                Add peppers
 *   -P, --pineapple              Add pineapple
 *   -b, --bbq-sauce              Add bbq sauce
 *   -c, --cheese [type="marble"] Add the specified type of cheese [marble]
 */

server-tool.js

"use strict";
var program = require("cli-program");
program
    .name("Server Tool")
    .version("0.0.1")
    .option("-U, --db-user <string>", "User for connect to DB")
    .option("-P, --db-password <string>", "Password for connect to DB", null, ["no", "without"])
    .option("-S, --db-socket <path>", "Socket to connect");
program
    .command("install <plugin>")
    .alias("i")
    .description("Install additional plugin")
    .option("-R, --recursive [number]", "Recursive level", 1)
    .action(function (args, opts) {
        console.log("Plugin: %s", args.plugin);
        console.log("Recursive: %s", opts.recursive);
    });
program
    .command("search <keyword> [keywords...]")
    .alias("s")
    .description("Search information")
    .option("-R, --recursive", "Search recursive")
    .action(function (args, opts) {
        console.log("keyword: %s", JSON.stringify(args.keyword));
        console.log("keywords: %s", JSON.stringify(args.keywords));
        console.log("recursive: %s", JSON.stringify(opts.recursive));
    });
program.parse();

/**
 * $ node ./examples/server-tool.js --help
 * Server Tool
 *
 * Usage:
 *
 *   server-tool [options...] <command> [arguments...] [options...]
 *
 * Options:
 *
 *   -h, --help                 Show help
 *   --no-color,
 *   --color [value=null]       Disable/enable output colors
 *   -V, --version              Show version.
 *   -U, --db-user <string>     User for connect to DB
 *   --no-db-password,
 *   --without-db-password,
 *   -P, --db-password <string> Password for connect to DB
 *   -S, --db-socket <path>     Socket to connect
 *
 * Commands:
 *
 *   install (alias: i) <plugin>
 *     Install additional plugin
 *
 *   search (alias: s) <keyword> [keywords...]
 *     Search information
 */

/**
 * $ node ./examples/server-tool.js install --help
 * Server Tool
 *
 * Usage:
 *
 *   server-tool [options...] install <plugin> [options...]
 *
 * Description:
 *
 *   Install additional plugin
 *
 * General Options:
 *
 *   -h, --help                 Show help
 *   --no-color,
 *   --color [value=null]       Disable/enable output colors
 *   -V, --version              Show version.
 *   -U, --db-user <string>     User for connect to DB
 *   --no-db-password,
 *   --without-db-password,
 *   -P, --db-password <string> Password for connect to DB
 *   -S, --db-socket <path>     Socket to connect
 *
 * Command Options:
 *
 *   -h, --help                 Show help
 *   -R, --recursive [number=1] Recursive level
 */

More demos can be found in the examples directory.

License

MIT License

Copyright (c) 2018 Oleg Rodzewich

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.