Socket
Socket
Sign inDemoInstall

promptly

Package Overview
Dependencies
2
Maintainers
2
Versions
16
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

promptly

Simple command line prompting utility


Version published
Maintainers
2
Weekly downloads
1,463,669
decreased by-27.52%

Weekly downloads

Readme

Source

promptly

NPM version Downloads Build Status Coverage Status Dependency status Dev Dependency status

Simple command line prompting utility.

Installation

$ npm install promptly

API

.prompt(message, [options])

Prompts for a value, printing the message and waiting for the input.
Returns a promise that resolves with the input.

Available options:

NameDescriptionTypeDefault
defaultThe default value to use if the user provided an empty inputstringundefined
trimTrims the user inputbooleantrue
validatorA validator or an array of validatorsfunction/arrayundefined
retryRetry if any of the validators failbooleantrue
silentDo not print what the user typesbooleanfalse
replaceReplace each character with the specified string when silent is truestring''
inputInput stream to read fromStreamprocess.stdin
outputOutput stream to write toStreamprocess.stdout
timeoutTimeout in msnumber0
useDefaultOnTimeoutReturn default value if timed outbooleanfalse

The same options are available to all functions but with different default values.

Examples
  • Ask for a name:

    const promptly = require('promptly');
    
    (async () => {
        const name = await promptly.prompt('Name: ');
        console.log(name);
    })();
    
  • Ask for a name with a constraint (non-empty value and length > 2):

    const promptly = require('promptly');
    
    const validator = function (value) {
        if (value.length < 2) {
            throw new Error('Min length of 2');
        }
    
        return value;
    };
    
    (async () => {
        const name = await promptly.prompt('Name: ', { validator });
        // Since retry is true by default, promptly will keep asking for a name until it is valid
        // Between each prompt, the error message from the validator will be printed
        console.log('Name is:', name);
    })();
    
    
  • Same as above but do not retry automatically:

    const promptly = require('promptly');
    
    const validator = function (value) {
        if (value.length < 2) {
            throw new Error('Min length of 2');
        }
    
        return value;
    };
    
    (async () => {
        try {
            const name = await promptly.prompt('Name: ', { validator, retry: false });
            console.log('Name is:', name);
        } catch (err) {
            console.error('Invalid name:')
            console.error(`- ${err.message}`);
        }
    })();
    
  • Ask for a name with timeout:

    const promptly = require('promptly');
    
    (async () => {
        const name = await promptly.prompt('Name: ', { timeout: 3000 });
        console.log(name);
    })();
    

    It throws an Error("timed out") if timeout is reached and no default value is provided

Validators

The validators have two purposes: to check and transform input. They can be asynchronous or synchronous

const validator = (value) => {
    // Validation example, throwing an error when invalid
    if (value.length !== 2) {
        throw new Error('Length must be 2');
    }

    // Parse the value, modifying it
    return value.replace('aa', 'bb');
}

const asyncValidator = async (value) => {
    await myfunc();
    return value;
}

.confirm(message, [options])

Ask the user for confirmation, printing the message and waiting for the input.
Returns a promise that resolves with the answer.

Truthy values are: y, yes and 1. Falsy values are n, no, and 0.
Comparison is made in a case insensitive way.

The options are the same as prompt, except that trim defaults to false.

Examples
  • Ask to confirm something important:

    const promptly = require('promptly');
    
    (async () => {
        const answer = await promptly.confirm('Are you really sure? ');
    
        console.log('Answer:', answer);
    })();
    

.choose(message, choices, [options])

Ask the user to choose between multiple choices (array of choices), printing the message and waiting for the input.
Returns a promise that resolves with the choice.

The options are the same as prompt, except that trim defaults to false.

Examples
  • Ask to choose between:

    const promptly = require('promptly');
    
    (async () => {
        const choice = await promptly.choose('Do you want an apple or an orange? ', ['apple', 'orange']);
    
        console.log('Choice:', choice);
    })();
    

.password(message, [options])

Prompts for a password, printing the message and waiting for the input.
Returns a promise that resolves with the password.

The options are the same as prompt, except that trim and silent default to false and default is an empty string (to allow empty passwords).

Examples
  • Ask for a password:

    const promptly = require('promptly');
    
    (async () => {
        const password = await promptly.password('Type a password: ');
    
        console.log('Password:', password);
    })();
    
  • Ask for a password but mask the input with *:

    const promptly = require('promptly');
    
    (async () => {
        const password = await promptly.password('Type a password: ', { replace: '*' });
    
        console.log('Password:', password);
    })();
    

Tests

$ npm test
$ npm test -- --watch during development

License

Released under the MIT License.

Keywords

FAQs

Last updated on 06 Nov 2020

Did you know?

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

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc