GithubHelp home page GithubHelp logo

moxystudio / node-promptly Goto Github PK

View Code? Open in Web Editor NEW
149.0 12.0 13.0 504 KB

Simple command line prompting utility for nodejs

License: MIT License

JavaScript 100.00%
prompt choose cli command-line nodejs

node-promptly's Introduction

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:

Name Description Type Default
default The default value to use if the user provided an empty input string undefined
trim Trims the user input boolean true
validator A validator or an array of validators function/array undefined
retry Retry if any of the validators fail boolean true
silent Do not print what the user types boolean false
replace Replace each character with the specified string when silent is true string ''
input Input stream to read from Stream process.stdin
output Output stream to write to Stream process.stdout
timeout Timeout in ms number 0
useDefaultOnTimeout Return default value if timed out boolean false

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.

node-promptly's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-promptly's Issues

Typos on npm page

Doesn't look like it's in the Readme, but on the npm page go do a word find for 'promply' :)

A new line in promptly.password

When running the code below, there is a new line printed out.

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

screen shot 2018-10-02 at 12 16 52 am

typo in test.js

Do you want to test {silent:true} or {silent:false}?
it('should write input to stdout if silent is false', function (next) {
promptly.prompt('something: ', { silent: true }, function (err, value) {
expect(err).to.be(null);
expect(value).to.be('yeaa');
expect(stdout).to.contain('something: ');
expect(stdout).to.not.contain(value);
next();
});

Could you add engine property to your package.json ?

Please add the engine property to your package.json, to specify the node version compatibility.

{ "engines" : { "node" : ">=8.0" } }

Thank you!

We ran into issues with spread operator (es8+) while trying to update from 2.2.0 and targeting es6, and had to track down what happened. Thanks!

Asynchronous validator

Is there a way to asynchronously validate data ? It could wait for validator to call a callback or returning a Promise.

Weird formatting of colored prompt message

The prompt message seems to display strangely when a colored message is used. The cursor appears indented far to the right. When hitting backspace, the text moves back to where it should, but the cursor stays where it is. Once another key is pressed, the text goes back to it's indented location.

Both the colors and cli-color modules cause this to happen.

screen shot 2014-02-23 at 1 42 24 pm

Default value not honored with timeout

I have the following:

;(async () => {
    let yn = await prompt.prompt(`Y/n: `,{ timeout: 1000, default: 'y' })
    console.log(yn)
})()

Which throws this error after one second:

Y/n: (node:49417) UnhandledPromiseRejectionWarning: Error: timed out
    at prompt (/Users/danraeder/Documents/GitHub/GunNS/node_modules/promptly/lib/prompt.js:23:33)
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
    at async file:///Users/danraeder/Documents/GitHub/GunNS/server.js:18:24
(Use `node --trace-warnings ...` to show where the warning was created)
(node:49417) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:49417) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

timeout

A timeout option would be helpful.

Async validator

It would be nice to be able to provide an asynchronous validator

Changelog

Hey. Could you add changelog at least for major releases?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.