@fcostarodrigo/ask v3.2.0
Ask
Wrapper of yargs and enquirer libs to ask user for input.
Install
npm i @fcostarodrigo/askUsage
Command line arguments
Create command line arguments. Each command line argument can be passed through the command line, environment variables and .env file. If the argument is missing and required, the user is prompted for it. Arguments are required by default. The options --help and --version are created automatically.
Pass an object describing each command line argument, the returned promise is an object of the same shape with the values extracted.
import { askArgv } from "@fcostarodrigo/ask";
const { password } = await askArgv({
password: {
type: "password",
},
});Passing value using the command line.
node src/test.js --password xxx
# no promptPassing value using environment variable.
PASSWORD=xxx node src/test.js
# no promptPassing value using the .env file.
echo PASSWORD=xxx > .env
node src/test.js
# no promptPrompt the user for the missing value.
node src/test.js
# prompt for passwordFor each command line argument you can also specify:
yargsOverridesOverride yargs lib configuration.enquirerOverridesOverride enquirer lib configuration.defaultValueDefault value.optionsPossible options for strings and array types.requiredIf the value is required or not.
Positional arguments
import { askArgv } from "@fcostarodrigo/ask";
const { username, password } = await askArgv({
username: { type: "string", position: 0 },
password: { type: "password", position: 1 },
});node src/test.js john xxx.env location.
You can also pass the location of the .env file as the second parameter.
import { askArgv } from "@fcostarodrigo/ask";
const { username } = await askArgv({ username: { type: "string" } }, { dotEnvConfig: ".dev.env" });echo USERNAME=john > .dev.env
node src/test.jsUser input
You can prompt the user in the middle of your program without defining new command line arguments.
import { ask } from "@fcostarodrigo/ask";
const password = await ask({ name: "password", type: "password" });Environment variables only
You can use askEnv to get values from environment variables alone. An error will be thrown if the environment variable is required, missing and there is no default value for it. You can pass dotEnvConfig as a field of the object of the second argument. The value will be parsed according to the type. Arrays are split by a single , and booleans are true if they match the string true when converted to lower case.
const { username, password } = askEnv({
username: { type: "string" },
password: { type: "password" },
});requiredIf the value is required or not.defaultValueDefault value.optionsArray of allowed values.
Supported types
| Type | options | yargs | enquirer |
|---|---|---|---|
| array | no | array | list |
| array | yes | array | auto complete |
| boolean | boolean | confirm | |
| number | number | numeral | |
| string | no | string | input |
| string | yes | string | auto complete |
| password | string | invisible |