🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

getopts

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

getopts

Parse CLI arguments.

2.3.0
latest
Version published
Weekly downloads
2.2M
4.15%
Maintainers
1
Weekly downloads
 
Created

What is getopts?

The getopts npm package is a lightweight and fast option parser for Node.js. It is used to parse command-line options and arguments in a simple and efficient manner.

What are getopts's main functionalities?

Basic Option Parsing

This feature allows you to parse command-line options and arguments. The code sample demonstrates how to use getopts to parse the command-line arguments passed to a Node.js script.

const getopts = require('getopts');
const options = getopts(process.argv.slice(2));
console.log(options);

Default Values

This feature allows you to set default values for options. The code sample shows how to provide default values for the 'name' and 'age' options.

const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
  default: {
    name: 'defaultName',
    age: 25
  }
});
console.log(options);

Aliases

This feature allows you to define aliases for options. The code sample demonstrates how to set up aliases for the 'name' and 'age' options.

const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
  alias: {
    n: 'name',
    a: 'age'
  }
});
console.log(options);

Boolean Options

This feature allows you to specify which options should be treated as boolean. The code sample shows how to define 'verbose' and 'debug' as boolean options.

const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
  boolean: ['verbose', 'debug']
});
console.log(options);

Unknown Option Handling

This feature allows you to handle unknown options. The code sample demonstrates how to log an error message for unknown options and prevent them from being included in the parsed options.

const getopts = require('getopts');
const options = getopts(process.argv.slice(2), {
  unknown: (option) => {
    console.error(`Unknown option: ${option}`);
    return false;
  }
});
console.log(options);

Other packages similar to getopts

FAQs

Package last updated on 15 Feb 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts