Giter Site home page Giter Site logo

enquirer / prompt-base Goto Github PK

View Code? Open in Web Editor NEW
23.0 4.0 1.0 168 KB

This repository has been archived, use Enquirer instead.

Home Page: https://github.com/enquirer/enquirer

License: MIT License

JavaScript 100.00%
enquirer readline prompt cli terminal questions

prompt-base's Introduction

prompt-base NPM version NPM monthly downloads NPM total downloads Linux Build Status Windows Build Status

Base prompt module used for creating custom prompts.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Install

Install with npm:

$ npm install --save prompt-base

Release history

See the changelog for detailed release history.

What is this?

prompt-base is a node.js library for creating command line prompts. You can use prompt-base directly for simple input prompts, or as a "base" for creating custom prompts:

Usage

See the examples folder for additional usage examples.

var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'color',
  message: 'What is your favorite color?'
});

// promise
prompt.run()
  .then(function(answer) {
    console.log(answer);
    //=> 'blue'
  })

// or async
prompt.ask(function(answer) {
  console.log(answer);
  //=> 'blue'
});

You can also pass a string directly to the main export:

var prompt = require('prompt-base')('What is your favorite color?');
  
prompt.run()
  .then(function(answer) {
    console.log(answer);
  })

Custom prompts

Inherit

var Prompt = require('prompt-base');

function CustomPrompt(/*question, answers, rl*/) {
  Prompt.apply(this, arguments);
}

Prompt.extend(CustomPrompt);

API

Create a new Prompt with the given question object, answers and optional instance of readline-ui.

Params

  • question {Object}: Plain object or instance of prompt-question.
  • answers {Object}: Optionally pass an answers object from a prompt manager (like enquirer).
  • ui {Object}: Optionally pass an instance of readline-ui. If not passed, an instance is created for you.

Example

var prompt = new Prompt({
  name: 'color',
  message: 'What is your favorite color?'
});

prompt.ask(function(answer) {
  console.log(answer);
  //=> 'blue'
});

Modify the answer value before it's returned. Must return a string or promise.

  • returns {String}

Example

var answers = {};
var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'name',
  message: 'What is your name?',
  transform: function(input) {
    return input.toUpperCase();
  }
});

Validate user input on keypress events and the answer value when it's submitted by the line event (when the user hits enter. This may be overridden in custom prompts. If the function returns false, either question.errorMessage or the default validation error message (invalid input) is used. Must return a boolean, string or promise.

  • returns {Boolean}

Example

var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'first',
  message: 'What is your name?',
  errorMessage: 'alphabetical characters only',
  validate: function(input) {
    var str = input ? input.trim() : '';
    var isValid = /^[a-z]+$/i.test(str);
    if (this.state === 'submitted') {
      return str.length > 10 && isValid;
    }
    return isValid;
  }
});

A custom .when function may be defined to determine whether or not a question should be asked at all. Must return a boolean, undefined, or a promise.

  • returns {Boolean}

Example

var answers = {};
var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'name',
  message: 'What is your name?',
  when: function(answers) {
    return !answers.name;
  }
});

Run the prompt with the given callback function.

Params

  • callback {Function}
  • returns {undefined}

Example

var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'name',
  message: 'What is your name?'
});

prompt.ask(function(answer) {
  console.log(answer);
});

Run the prompt and resolve answers. If when is defined and returns false, the prompt will be skipped.

Params

  • answers {Object}: (optional) When supplied, the answer value will be added to a property where the key is the question name.
  • returns {Promise}

Example

var answers = {};
var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'name',
  message: 'What is your name?'
});

prompt.run(answers)
  .then(function(answer) {
    console.log(answer);
    console.log(answers);
  });

Get the answer to use. This can be overridden in custom prompts.

  • returns {String}

Example

console.log(prompt.getDefault());

Get the error message to use. This can be overridden in custom prompts.

  • returns {String}

Example

console.log(prompt.getError());

Get the help message to use. This can be overridden in custom prompts.

  • returns {String}

Example

console.log(prompt.getHelp());

Get the answer to use. This can be overridden in custom prompts.

  • returns {String}

Example

console.log(prompt.getAnswer());

(Re-)render the prompt message, along with any help or error messages, user input, choices, list items, and so on. This is called to render the initial prompt, then it's called again each time the prompt changes, such as on keypress events (when the user enters input, or a multiple-choice option is selected). This method may be overridden in custom prompts, but it's recommended that you override the more specific render "status" methods instead.

  • returns {undefined}

Example

prompt.ui.on('keypress', prompt.render.bind(prompt));

Format the prompt message.

  • returns {String}

Example

var answers = {};
var Prompt = require('prompt-base');
var prompt = new Prompt({
  name: 'name',
  message: 'What is your name?',
  transform: function(input) {
    return input.toUpperCase();
  }
});

Called by render to render the readline line when prompt.status is anything besides answered, which includes everything except for error and help messages.

  • returns {String}

Called by render to add a footer after the message body.

  • returns {String}

Called by render to render a help message when the prompt.status is initialized or help (usually when the prompt is first rendered). Calling this method changes the prompt.status to "interacted", and as such, by default, the message is only displayed until the user interacts. By default the help message is positioned to the right of the prompt "question". A custom help message may be defined on options.helpMessage.

Params

  • valid {boolean|string|undefined}
  • returns {String}

Render an error message in the prompt, when valid is false or a string. This is used when a validation method either returns false, indicating that the input was invalid, or the method returns a string, indicating that a custom error message should be rendered. A custom error message may also be defined on options.errorMessage.

Params

  • valid {boolean|string|undefined}
  • returns {String}

Mask user input. Called by renderBody, this is an identity function that does nothing by default, as it's intended to be overwritten in custom prompts, such as prompt-password.

  • returns {String}

Render the user's "answer". Called by render when the prompt.status is changed to answered.

  • returns {String}

Get action name, or set action name with the given fn. This is useful for overridding actions in custom prompts. Actions are used to move the pointer position, toggle checkboxes and so on

Params

  • name {String}
  • fn {Function}
  • returns {Object|Function}: Returns the prompt instance if setting, or the action function if getting.

Move the cursor in the given direction when a keypress event is emitted.

Params

  • direction {String}
  • event {Object}

Default error event handler. If an error listener exist, an error event will be emitted, otherwise the error is logged onto stderr and the process is exited. This can be overridden in custom prompts.

Params

  • err {Object}

Re-render and pass the final answer to the callback. This can be replaced by custom prompts.

Ensures that events for event name are only registered once and are disabled correctly when specified. This is different from .once, which only emits once.

Example

prompt.only('keypress', function() {
  // do keypress stuff
});

Mutes the output stream that was used to create the readline interface, and returns a function for unmuting the stream. This is useful in unit tests.

  • returns {Function}

Example

// mute the stream
var unmute = prompt.mute();

// unmute the stream
unmute();

Pause the readline and unmute the output stream that was used to create the readline interface, which is process.stdout by default.

Resume the readline input stream if it has been paused.

  • returns {undefined}

Getter for getting the choices array from the question.

  • returns {Object}: Choices object

Getter that returns question.message after passing it to format.

  • returns {String}: A formatted prompt message.

Getter/setter for getting the checkbox symbol to use.

  • returns {String}: The formatted symbol.

Example

// customize
prompt.symbol = '[ ]';

Getter/setter that returns the prefix to use before question.message. The default value is a green ?.

  • returns {String}: The formatted prefix.

Example

// customize
prompt.prefix = ' ❤ ';

Static convenience method for running the .ask method. Takes the same arguments as the contructror.

Params

  • question {Object}: Plain object or instance of prompt-question.
  • answers {Object}: Optionally pass an answers object from a prompt manager (like enquirer).
  • ui {Object}: Optionally pass an instance of readline-ui. If not passed, an instance is created for you.
  • callback {Function}
  • returns {undefined}

Example

var prompt = require('prompt-base');
  .ask('What is your favorite color?', function(answer) {
    console.log({color: answer});
    //=> { color: 'blue' }
  });

Static convenience method for running the .run method. Takes the same arguments as the contructror.

Params

  • question {Object}: Plain object or instance of prompt-question.
  • answers {Object}: Optionally pass an answers object from a prompt manager (like enquirer).
  • ui {Object}: Optionally pass an instance of readline-ui. If not passed, an instance is created for you.
  • returns {Promise}

Example

var prompt = require('prompt-base');
  .run('What is your favorite color?')
  .then(function(answer) {
    console.log({color: answer});
    //=> { color: 'blue' }
  });

Create a new Question. See prompt-question for more details.

Params

  • options {Object}
  • returns {Object}: Returns an instance of prompt-question

Example

var question = new Prompt.Question({name: 'foo'});

Create a new Choices object. See prompt-choices for more details.

Params

  • choices {Array}: Array of choices
  • returns {Object}: Returns an intance of Choices.

Example

var choices = new Prompt.Choices(['foo', 'bar', 'baz']);

Create a new Separator object. See choices-separator for more details.

Params

  • separator {String}: Optionally pass a string to use as the separator.
  • returns {Object}: Returns a separator object.

Example

new Prompt.Separator('---');

Events

prompt

Emitted when a prompt (plugin) is instantiated, after the readline interface is created, but before the actual "question" is asked.

Example usage

enquirer.on('prompt', function(prompt) {
  // do stuff with "prompt" instance
});

ask

Emitted when the actual "question" is asked.

Example usage

Emit keypress events to supply the answer (and potentially skip the prompt if the answer is valid):

enquirer.on('ask', function(prompt) {
  prompt.rl.input.emit('keypress', 'foo');
  prompt.rl.input.emit('keypress', '\n');
});

Change the prompt message:

enquirer.on('ask', function(prompt) {
  prompt.message = 'I..\'m Ron Burgundy...?';
});

answer

Emitted when the final (valid) answer is submitted, and custom validation function (if defined) returns true.

(An "answer" is the final input value that's captured when the readline emits a line event; e.g. when the user hits enter)

Example usage

enquirer.on('answer', function(answer) {
  // do stuff with answer
});

In the wild

The following custom prompts were created using this library:

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Please read the contributing guide for advice on opening issues, pull requests, and coding standards.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
170 jonschlinkert
6 doowb
1 sbj42

Author

Jon Schlinkert

License

Copyright © 2017, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.6.0, on October 20, 2017.

prompt-base's People

Contributors

doowb avatar jonschlinkert avatar sbj42 avatar

Stargazers

 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

prompt-base's Issues

replace ttys?

Tests appear to be failing because of the issue described here. Given that the issue has been open for a couple of years, we should probably just find a different solution or fork it.

The following characters don't get displayed when typed -=\/|:;<>,?`[]{}

-=/|:;<>,?`[]{} None of the preceding characters get displayed on the prompt when typed. They will display if another character is typed after they are typed. The correct value does get returned by the run function, even if it doesn't get displayed correctly when it's typed.

This is just a guess, but this is probably related to #4.

Periods don't get displayed.

When running a prompt, periods don't get displayed when they are typed. If you type "." you'll see nothing. If you type "a", then the period will suddenly display and the prompt will read ".a".

Boolean Type Clarification

Working on the dev branch, I ran the boolean example node examples/boolean.js which presents me with the following prompt.

screen shot 2018-07-05 at 10 21 54 am

As a new user, my first inclination was that I would be able use the arrow keys to move up/down and alternate between true and false. However, it initially seemed that no matter what key I pressed, the value would switch to false and it would be stuck there.

I couldn't figure out how to get it back to true, so I thought there might be a bug. I dug into the code, and I found that every keypress is run through this function:

cast(val) {
  return /^[ty1]/i.test(val);
}

The return value of that function is set as the new value of the prompt. So, with the boolean prompt, you have to hit either "t", "y", or "1" to set the value to true and every other keypress will be false.

I just wanted to bring this up with you guys and let you know that this was pretty confusing for a new user. I was looking at some other prompts and the prompt-confirm package is the interface I would expect for a boolean type.

Some options I'm thinking for making this easier for newcomers:

  • Just add a help message to all boolean type prompts that says "Press y, t, or 1 for true" (Not my favorite one)
  • The prompt-confirm package becomes the new boolean type. I personally like the [Y/n] interface. It's very familiar from working with linux and other cli tools.
  • The boolean type becomes a prompt-choices with default list of values of true/false and you can only select one. This would allow you to use the arrow keys and other standard navigation options and give a visual of the available choices. This seems the most intuitive to me.

Let me know what you guys think!

this.ui.write() is not a function

Errors comes from confirm and autocomplete and possibly more.

~/dev/enquirer/examples master ✓  
% 1 ❯ node autocomplete.js                                                                            September 12, 01:12:02
? Select a state to travel from Kansasreadline.js:953
            throw err;
            ^

TypeError: this.ui.write is not a function
    at Prompt.onSubmit (/home/charlike/dev/enquirer/examples/plugins/autocomplete.js:109:11)
    at UI.Emitter.emit (/home/charlike/dev/enquirer/node_modules/component-emitter/index.js:133:20)
    at emitOne (events.js:96:13)
    at Interface.emit (events.js:188:7)
    at Interface._onLine (readline.js:232:10)
    at Interface._line (readline.js:574:8)
    at Interface._ttyWrite (readline.js:851:14)
    at ReadStream.onkeypress (readline.js:119:10)
    at emitTwo (events.js:111:20)
    at ReadStream.emit (events.js:191:7)

and

~/dev/enquirer/examples master ✓  
% ❯ node confirm.js                                                                                   September 12, 01:14:23
? Foo? Noreadline.js:953
            throw err;
            ^

TypeError: this.ui.write is not a function
    at Confirm.onSubmit (/home/charlike/dev/enquirer/examples/node_modules/enquirer-prompt-confirm/index.js:71:11)
    at UI.on (/home/charlike/dev/enquirer/node_modules/component-emitter/index.js:65:8)
    at UI.Emitter.emit (/home/charlike/dev/enquirer/node_modules/component-emitter/index.js:133:20)
    at emitOne (events.js:96:13)
    at Interface.emit (events.js:188:7)
    at Interface._onLine (readline.js:232:10)
    at Interface._line (readline.js:574:8)
    at Interface._ttyWrite (readline.js:851:14)
    at ReadStream.onkeypress (readline.js:119:10)
    at emitTwo (events.js:111:20)

Option to remove on exit

I'm using prompt-confirm for a single "Are you sure? (y/N)" confirmation in a delete operation. There is no point in me keeping this in stdout. It'd be great if there was a way to have it auto-removed on exit.

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.