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

get-options

v1.2.0

Published

JavaScript's answer to getopts. Simple, obvious, and direct.

Downloads

2,502

Readme

GetOptions

Build status: TravisCI Build status: AppVeyor

The JavaScript equivalent of getopts. No frills, no bullshit; nothing but cold, hard option extraction.

Use this module if you

  • Are happy validating and type-checking input yourself
  • Don't mind writing your own documentation
  • Prefer a hands-on approach without pointless array-fiddling

This lets you extract options so this...

... gets filtered down to this:

... with everything neatly sorted into one little object:

let result = {
    options: {
        logPath: "/var/log/stuff.txt",
        verbose: true
    },
    argv: [
        "generate",
        "all-files"
    ]
};

That's seriously all.

Example

getOpts(process.argv, {
    "-v, --verbose":    "",
    "-l, --log-level":  "[level]",
    "-p, --log-path":   "<path>",
    "-s, --set-config": "<name> <value>",
    "-f, --files":      "<search-path> <variadic-file-list...>"
});

Left column:
Short and long forms of each defined option, separated by commas.

Right column:
Arguments each option takes, if any.

Note: There's no requirement to enclose each parameter's name with < > [ ] ( ). These characters are just permitted for readability, and are ignored by the function when it runs. They're allowed because some authors might find them easier on the eyes than simple space-separation.

When omitted:
If you don't define any options, the function takes a "best guess" approach by absorbing anything with a dash in front of it. Specifically, the following assumptions are made:

  • Anything beginning with at least one dash is an option name
  • Options without arguments mean a boolean true
  • Option-reading stops at --
  • Anything caught between two options becomes the first option's value

Don't rely on this approach to give you foolproof results. Read about the caveats here.

Result

The value that's assigned to each corresponding .options property is either:

  • Boolean true if the option doesn't take any parameters (e.g., "--verbose": "")
  • A string holding the value of the option's only argument (e.g., "--log-path": "path")
  • An array if more than one parameter was specified. (e.g., "-s, --set-config": "name value")

Given the earlier example, the following line...

... would yield:

let result = {
    argv:    ["subcommand", "param"],
    options: {
        files:   ["/search/path", "1.jpg", "2.txt", "3.gif"],
        logPath: "/path/to",
        verbose: true
    }
};

I'm sure you get it by now.

That's it?

Yeah, that's it. You want fancy subcommands? Just leverage the .argv property of the returned object:

let subcommands = {
    generate: function(whichFiles){
        console.log("Let's generate... " + whichFiles);
    }
};

subcommands[ result.argv[0] ].apply(null, result.argv.slice(1));
/** -> Outputs "Let's generate... all-files" */

This would work too, if you're an eval kinda guy:

function generate(whichFiles){ /* ... */ }

eval(result.argv[0]).apply(null, result.argv.slice(1));

Obviously you'd be checking if the function existed and all that jazz. But that's up to you.

Further reading

I've broken the more convoluted documentation into different files, in an effort to keep this readme file terse:

Reminders

  • No typecasting is performed on user input. Values will always be stored as strings.
  • This is pure JavaScript, so it's not reliant on Node to work. Feel free to use it in a browser environment or whatever.
  • The array that's passed to the function isn't modified. If you want to overwrite the values stored in process.argv, do so by assignment:This is by design. It's not reasonable to assume developers will expect the contents of the array to be automatically shifted as options are being plucked from it.
  • As you'd expect, the first two values in process.argv contain the paths of the Node executable and the currently-running script. These have been omitted from the examples documented here (perhaps misleadingly, but done so for brevity's sake). In production, you'd probably want to pass process.argv.slice(2) to getOpts or something.

Why?

Yeah, there's billions of CLI-handling modules on NPM. Among the most well-known and popular are Commander.JS and yargs. Since I'm a control freak, though, I prefer doing things my way. So I developed a solution that'd permit more idiosyncratic approaches than those offered by "mainstream" option modules.