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

optant

v2.0.0

Published

Minimalistic command line option parsing for Node

Downloads

4

Readme

Optant

Minimalistic command line option parsing for Node scripts.

Synopsis

Optant is a tiny library that parses any arguments and options supplied to your script on the command line. It's perfect when you need to write a script that reads some arguments and/or options from the command line, but don't want to invest time and energy into constructing a complex setup with commander or other more advanced tools.

Optant can be used in two ways:

  • Simply calling optant() with no arguments will return an array containing two elements: the first is an array of supplied positional arguments, and the second is an object containing supplied options. See Basic usage.
  • Alternatively, you can call optant with a callback function that will receive the parsed arguments and options. Optant wil then wait for the function to return its result (or error) and output it appropriately. See Advanced usage.

Basic usage

const optant = require('optant');
const [argv,options] = optant();

Optant will recognize short and long options, beginning with one or two dashes, and optionally followed by an equals sign and a string value. These will be returned in the options object. All other arguments will be returned in the argv array.

Options without values will be treated as boolean, options with number values will be converted to numbers, other values will be returned as strings. Arguments that are numbers will also be converted to numbers.

Option names that include dashes will be camelCased.

Examples

| command line | argv | options | | ------------ | ---- | ------- | | yourscript inputfile outputfile | ["inputfile","outputfile"] | {} | | yourscript -v | [] | {v:true} | | yourscript -abc | [] | {a:true,b:true,c:true} | | yourscript --help | [] | {help:true} | | yourscript --char-count=100 | [] | {charCount:100} | | yourscript 20 30 --output=outputfile | [20,30] | {output:"outputfile"} | | yourscript -b --count=10 inputfile | ["inputfile"] | {b:true, output:10} |

NOTE Option arguments without equals signs are not supported.

Advanced usage

Alternatively, you can use Optant as scaffolding for your shell script. It will parse the options and arguments, optionally print out the results, and exit the process with the correct exit code.

optant( (argv,options) => {
  // do stuff, then return a result or throw an error
})

Call optant with a callback, which will be called with an array of positional arguments and an object of boolean, string or numerical options. The callback can return a result or a promise, or nothing.

Once a result is returned, or the promise is resolved, optant will print out any results and exit the process.

  • Returned scalars will be printed to stdout, and the process will exit with exit code 0.
  • Returned objects will be printed to stdout as formatted JSON, and the process will exit with code 0. If the returned object is not JSONable, the process will exit with code 1, and an error message will be displayed on stderr.
  • If an error is thrown, it will be reported to stderr and the process will exit with code 1. If the error that was thrown includes a numerical property .code, that will used instead.
  • If nothing (or undefined) is returned, the process will print nothing and exit with code 0.

ES6 destructuring and default values

You can also take advantage of argument destructuring in ES6 to receive the arguments and the options as named variables, and provide them with default values. Consider the following script to appreciate the possibilities:

const optant = require('optant');

optant( ([
    inputfile, 
    outputfile = inputfile+'.out'
  ],{
    s = 0, skip = s, 
    n = 10, lines = n,
    force,
    h, help = h,
    v, version = v
  }) => {
  
  // version = --version or -v
  if (version) return 'v1.0';
  
  // help = --help or -h
  if (help || h || !inputfile) return 'Usage: myscript inputfile [outputfile] [--force] [-n|--lines=10] [-s|--skip=0]';
  
  // script
  // force = --force 
  if (fs.existsSync(outputfile) && !force && !f) {
    throw new Error(`${outputfile} exists. Use --force to overwrite.`);
  }
  var input = fs.readFileSync(inputfile,'utf8');
  // skip = --skip or --s
  // lines = --lines or -n
  var output = input.split(/\n/).slice(skip,skip+lines).join('\n');
  fs.writeFileSync(outputfile);
});

Recipes

Sync

optant((argv,options) => {
  var result = ...
  return result;    // or throw to signal an error
});

Old-Style Async

optant( (argv,options) => new Promise(resolve,reject) {
  oldStyleAsyncFunction(..., (err,res) => {
    if (err) return reject(err);
    var result = ...
    resolve(result);  // or reject to signal an error
  })
});

Promise

optant( (argv,options) => {
  return promisefulFunction(...)
  .then(res=>{
    var result = ...
    return result; // or throw to signal an error
  })
});

Async/Await


optant( async (argv,options) => {
  var result = await asyncFunction(...);
  return result; // or throw to signal an error
});

Installation

npm install optant or yarn add optant

License

MIT License - Use this software as you please, as long as you include the license notice in any distributions.