Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

prompt-base

Package Overview
Dependencies
Maintainers
2
Versions
41
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

prompt-base

Base prompt module used for creating custom prompt types for Enquirer.

  • 0.8.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
50K
increased by23.99%
Maintainers
2
Weekly downloads
 
Created
Source

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

Base prompt module used for creating custom prompt types for Enquirer.

Install

Install with npm:

$ npm install --save prompt-base

Release history

See the changlog for details.

Usage

See the examples folder for more detailed usage examples.

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

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

API

Prompt

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'
});

.format

Returns a formatted prompt message.

  • returns {String}

.transform

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

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) {
    return input && !/^[a-z]+$/i.test(input);
  }
});

.when

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() {
    return !answers.name;
  }
});

.ask

Run the prompt with the given callback function. This method is similar to run, but is async (does not return a promise), and does not call when, transform or validate. This may be overridden in custom prompts.

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

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);
  });

.render

(Re-)render the current prompt string. This is called to render the initial prompt, then it's called again each time something changes, like as the user types an input value, or a multiple-choice option is selected. This method may be overridden in custom prompts.

Example

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

.move

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

Params

  • direction {String}
  • event {Object}

.onEnterKey

Default return event handler. This may be overridden in custom prompts.

Params

  • event {Object}

.onError

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}

.onKeypress

Default keypress event handler. This may be overridden in custom prompts.

Params

  • event {Object}

.onNumberKey

Default number event handler. This may be overridden in custom prompts.

Params

  • event {Object}

.onSpaceKey

Default space event handler. This may be overridden in custom prompts.

Params

  • event {Object}

.onSubmit

When the answer is submitted (user presses enter key), re-render and pass answer to callback. This may be replaced by custom prompts.

Params

  • input {Object}

.onTabKey

Default tab event handler. This may be overridden in custom prompts.

Params

  • event {Object}

.mute

Proxy to readline.write for manually writing output. When called, rl.write() will resume the input stream if it has been paused.

  • returns {undefined}

Example

prompt.write('blue\n');
prompt.write(null, {ctrl: true, name: 'l'});

.choices

Getter for getting the choices array from the question.

  • returns {Object}: Choices object

.message

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

  • returns {String}: A formatted prompt message.

.prefix

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

  • returns {String}: The formatted prefix.

Example

prompt.prefix = ' ❤ ';

.Separator

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('---');

Examples

Instantiate

The main purpose of this library is to serve as a base for other libraries to create custom prompt types. However, the main export is a function that can be instantiated to run basic "input" prompts.

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

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

// promise
prompt.run()
  .then(function(answers) {
    console.log(answers);
    //=> {first: 'Jon'}
  });

Inherit

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

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

Prompt.extend(CustomPrompt);

Debugging

Debugging readline issues can be a pain. If you're experiencing something that seems like a bug, please let us know about it. If you happen to be in the mood for debugging, here are some suggestions and/or places to look to help you figure out what's happening.

Tips

  • call process.exit() after logging out the value as you're debugging. This not only stops the process immediately, letting you know if the method was even executed, but it's also more likely to make whatever you're logging out visible before it's overwritten by the readline
  • Wrap the value in an array: like console.log([foo]) instead of console.log(foo). I do this when debugging just about anything, as it forces the value to be rendered literally, instead of being formatted as output for the terminal.

In prompt-base (this module):

Log out the answer value or any variants, like this.answer, or input in methods like onSubmit, and submitAnswer.

console.log([this.answer]);
// etc...

In the .action method, log out the arguments object:

utils.action = function(state, str, key) {
  console.log([arguments]);
  process.exit();
  // other code
};

readline-utils

In the .normalize method in readline-utils, log out the arguments object:

utils.normalize = function(s, key) {
  console.log([arguments]);
  process.exit();
  // other code
};

readline-ui

Log out the keypress events in the listener.

Misc

In libraries with prompt-* or readline-*, or enquirer-* in the name, look for places where something is .emiting, or listening with .on or .only (which simply wraps .on to ensure that events aren't stacked when nested prompts are called), and log out the value there.

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.

Contributors

CommitsContributor
77jonschlinkert
6doowb

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

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

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 May 13, 2017.

Keywords

FAQs

Package last updated on 13 May 2017

Did you know?

Socket

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
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc