What is has-flag?
The has-flag npm package is a simple utility that checks if a specific flag is provided in the command line arguments (process.argv). It is commonly used to determine if a flag is set when running a Node.js script from the terminal.
What are has-flag's main functionalities?
Check for the presence of a command line flag
This feature allows you to check if a flag, such as '--unicorn', is passed to the script. The code sample demonstrates how to use has-flag to check for the 'unicorn' flag and log a message if it is present.
const hasFlag = require('has-flag');
if (hasFlag('unicorn')) {
console.log('We have a unicorn!');
}
Other packages similar to has-flag
minimist
Minimist is a more comprehensive command line argument parsing library. Unlike has-flag, which only checks for the existence of flags, minimist parses all arguments into a structured object, making it easier to work with multiple types of command line parameters.
commander
Commander is a complete solution for building command line applications in Node.js. It provides a high-level API for parsing command line options, as well as a variety of other features such as subcommands and automated help generation. Commander is more feature-rich compared to has-flag, which is focused solely on flag detection.
yargs
Yargs is another full-featured command line option parser that offers advanced features like command chaining, argument validation, and automatic help generation. It is more complex and feature-complete than has-flag, which is a minimalistic tool for flag checking.
has-flag
Check if argv
has a specific flag
Install
$ npm install has-flag
Usage
import hasFlag from 'has-flag';
hasFlag('unicorn');
hasFlag('--unicorn');
hasFlag('f');
hasFlag('-f');
hasFlag('foo=bar');
hasFlag('foo');
hasFlag('rainbow');
$ node foo.js -f --unicorn --foo=bar -- --rainbow
API
hasFlag(flag, argv?)
Returns a boolean for whether the flag exists.
It correctly stops looking after an --
argument terminator.
flag
Type: string
CLI flag to look for. The --
prefix is optional.
argv
Type: string[]
Default: process.argv
CLI arguments.