Git Product home page Git Product logo

prompt's Introduction

prompt Build Status Npm package version

A beautiful command-line prompt for node.js

Features

  • prompts the user for input
  • supports validation and defaults
  • hides passwords

Usage

Using prompt is relatively straight forward. There are two core methods you should be aware of: prompt.get() and prompt.addProperties(). Their methods take strings representing property names in addition to objects for complex property validation (and more). There are a number of examples that you should examine for detailed usage.

Getting Basic Prompt Information

Getting started with prompt is easy. Lets take a look at examples/simple-prompt.js:

  var prompt = require('prompt');

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get two properties from the user: username and email
  //
  prompt.get(['username', 'email'], function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
  });

This will result in the following command-line output:

  $ node examples/simple-prompt.js
  prompt: username: some-user
  prompt: email: [email protected]
  Command-line input received:
    username: some-user
    email: [email protected]

If no callback is passed to prompt.get(schema), then it returns a Promise, so you can also write:

const {username, email} = await prompt.get(['username', 'email']);

Prompting with Validation, Default Values, and More (Complex Properties)

In addition to prompting the user with simple string prompts, there is a robust API for getting and validating complex information from a command-line prompt. Here's a quick sample:

  var schema = {
    properties: {
      name: {
        pattern: /^[a-zA-Z\s\-]+$/,
        message: 'Name must be only letters, spaces, or dashes',
        required: true
      },
      password: {
        hidden: true
      }
    }
  };

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get two properties from the user: name, password
  //
  prompt.get(schema, function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  name: ' + result.name);
    console.log('  password: ' + result.password);
  });

Pretty easy right? The output from the above script is:

  $ node examples/property-prompt.js
  prompt: name: nodejitsu000
  error:  Invalid input for name
  error:  Name must be only letters, spaces, or dashes
  prompt: name: Nodejitsu Inc
  prompt: password:
  Command-line input received:
    name: Nodejitsu Inc
    password: some-password

Valid Property Settings

prompt understands JSON-schema with a few extra parameters and uses revalidator for validation.

Here's an overview of the properties that may be used for validation and prompting controls:

  {
    description: 'Enter your password',     // Prompt displayed to the user. If not supplied name will be used.
    type: 'string',                 // Specify the type of input to expect.
    pattern: /^\w+$/,                  // Regular expression that input must be valid against.
    message: 'Password must be letters', // Warning message to display if validation fails.
    hidden: true,                        // If true, characters entered will either not be output to console or will be outputed using the `replace` string.
    replace: '*',                        // If `hidden` is set it will replace each hidden character with the specified string.
    default: 'lamepassword',             // Default value to use if no value is entered.
    required: true                        // If true, value entered must be non-empty.
    before: function(value) { return 'v' + value; } // Runs before node-prompt callbacks. It modifies user's input
  }

Alternatives to pattern include format and conform, as documented in revalidator.

Supported types are string, boolean, number, integer, array

Using type: 'boolean' accepts case insensitive values 'true', 't', 'false', 'f'

Using type: 'array' has some special cases.

  • description will not work in the schema if type: 'array' is defined.
  • maxItems takes precedence over minItems.
  • Arrays that do not have maxItems defined will require users to SIGINT (^C) before the array is ended.
  • If SIGINT (^C) is triggered before minItems is met, a validation error will appear. This will require users to SIGEOF (^D) to end the input.

For more information on things such as maxItems and minItems, refer to the revalidator repository.

Alternate Validation API:

Prompt, in addition to iterating over JSON-Schema properties, will also happily iterate over an array of validation objects given an extra 'name' property:

  var prompt = require('../lib/prompt');

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get two properties from the user: username and password
  //
  prompt.get([{
      name: 'username',
      required: true
    }, {
      name: 'password',
      hidden: true,
      conform: function (value) {
        return true;
      }
    }], function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  password: ' + result.password);
  });

Backward Compatibility

Note that, while this structure is similar to that used by prompt 0.1.x, that the object properties use the same names as in JSON-Schema. prompt 0.2.x is backward compatible with prompt 0.1.x except for asynchronous validation.

Skipping Prompts

Sometimes power users may wish to skip prompts and specify all data as command line options. if a value is set as a property of prompt.override prompt will use that instead of prompting the user.

  //prompt-override.js

  var prompt = require('prompt'),
      optimist = require('optimist')

  //
  // set the overrides
  //
  prompt.override = optimist.argv

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get two properties from the user: username and email
  //
  prompt.get(['username', 'email'], function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  username: ' + result.username);
    console.log('  email: ' + result.email);
  })

  //: node prompt-override.js --username USER --email EMAIL

It is also possible to skip prompts dynamically based on previous prompts. If an ask method is added, prompt will use it to determine if the prompt should be displayed. If ask returns true the prompt is displayed. otherwise, the default value or empty string are used.

  var schema = {
    properties: {
      proxy: {
        description: 'Proxy url',
      },
      proxyCredentials: {
        description: 'Proxy credentials',
        ask: function() {
          // only ask for proxy credentials if a proxy was set
          return prompt.history('proxy').value > 0;
        }
      }
    }
  };

  //
  // Start the prompt
  //
  prompt.start();

  //
  // Get one or two properties from the user, depending on
  // what the user answered for proxy
  //
  prompt.get(schema, function (err, result) {
    //
    // Log the results.
    //
    console.log('Command-line input received:');
    console.log('  proxy: ' + result.proxy);
    console.log('  credentials: ' + result.proxyCredentials);
  });

Adding Properties to an Object

A common use-case for prompting users for data from the command-line is to extend or create a configuration object that is passed onto the entry-point method for your CLI tool. prompt exposes a convenience method for doing just this:

  var obj = {
    password: 'lamepassword',
    mindset: 'NY'
  }

  //
  // Log the initial object.
  //
  console.log('Initial object to be extended:');
  console.dir(obj);

  //
  // Add two properties to the empty object: username and email
  //
  prompt.addProperties(obj, ['username', 'email'], function (err) {
    //
    // Log the results.
    //
    console.log('Updated object received:');
    console.dir(obj);
  });

Prompt history

You can use the prompt.history() method to get access to previous prompt input.

  prompt.get([{
    name: 'name',
    description: 'Your name',
    type: 'string',
    required: true
  }, {
    name: 'surname',
    description: 'Your surname',
    type: 'string',
    required: true,
    message: 'Please dont use the demo credentials',
    conform: function(surname) {
      var name = prompt.history('name').value;
      return (name !== 'John' || surname !== 'Smith');
    }
  }], function(err, results) {
    console.log(results);
  });

Customizing your prompt

Aside from changing property.message, you can also change prompt.message and prompt.delimiter to change the appearance of your prompt.

The basic structure of a prompt is this:

prompt.message + prompt.delimiter + property.message + prompt.delimiter;

The default prompt.message is "prompt," the default prompt.delimiter is ": ", and the default property.message is property.name. Changing these allows you to customize the appearance of your prompts! In addition, prompt supports ANSI color codes via the colors module for custom colors. For a very colorful example:

  var prompt = require("prompt");
  var colors = require("@colors/colors/safe");
  //
  // Setting these properties customizes the prompt.
  //
  prompt.message = colors.rainbow("Question!");
  prompt.delimiter = colors.green("><");

  prompt.start();

  prompt.get({
    properties: {
      name: {
        description: colors.magenta("What is your name?")
      }
    }
  }, function (err, result) {
    console.log(colors.cyan("You said your name is: " + result.name));
  });

If you don't want colors, you can set

var prompt = require('prompt');

prompt.colors = false;

Integration with streamlinejs

When integrating prompt with projects using streamlinejs such as the following

prompt.start();
function test_prompt(_){
    console.log(prompt.get(loadDataValues(), _).output);
}
test_prompt(_);

This will work, however the process is then stuck with a stdin stream still open. If you setup the traditional way (with callback) such as this

prompt.start();
function test_prompt(){
   prompt.get(loadDataValues(), function(err, data){
       console.log(data.output);
   });
}
test_prompt();

This works and ends correctly.

To resolve this we have added a new method to prompt, which will stop the stdin stream

//
// ### function stop ()
// Stops input coming in from stdin
//
prompt.stop = function () {
    if (prompt.stopped || !prompt.started) {
        return;
    }

    stdin.destroy();
    prompt.emit('stop');
    prompt.stopped = true;
    prompt.started = false;
    prompt.paused = false;
    return prompt;
}

And you can find an example in the example folder examples/prompt-streamline.js

/*
 * prompt-streamline._js: Example of how to use prompt with streamlinejs.
 *
 * calling syntax: _node prompt-streamline._js
 *
 */
var prompt = require('../lib/prompt');

function getSampleData(){
    return [
        {
            name: 'username',
            message: 'Enter a username'
        }
    ];
};

//
// Start the prompt
//
prompt.start();

function get_username_prompt(_){
    console.log(prompt.get(getSampleData(), _).username);
}

get_username_prompt(_);

//
// Clean the prompt
//
prompt.stop();

Disabling prompt's built-in SIGINT handling

By default, prompt prompt binds a process-killing event handler to the SIGINT event (CTRL+C). This allows easily exiting from prompts, but can prevent an app from executing other event handlers when an interrupt is received. In order to override this default behavior, pass a {noHandleSIGINT: true} option into prompt.start.

  //
  // Disable prompt's built-in SIGINT handling:
  //
  prompt.start({noHandleSIGINT: true});
  
  process.on('SIGINT', function() {
    console.log("This will execute when you hit CTRL+C");
    process.exit();
  });

Installation

  $ [sudo] npm install prompt

Running tests

  $ npm test

License: MIT

prompt's People

Contributors

3rd-eden avatar alessioalex avatar avianflu avatar badsyntax avatar benatkin avatar bmeck avatar bradfol avatar caleteeter avatar caub avatar coderarity avatar dabh avatar dcm avatar dominictarr avatar dsych avatar eagerod avatar gangstead avatar goatslacker avatar indexzero avatar indutny avatar jcrugzz avatar jfhbrook avatar jordanyaker avatar losttime avatar marak avatar mmalecki avatar pksunkara avatar rubbingalcoholic avatar selfcontained avatar southern avatar yawnt 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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prompt's Issues

Prompt using utile wrong bug

The signature has changed. The "capitalize" function is no longer part of the "inflect" submodule but is on utile directly
so

capitalize = utile.inflect.capitalize, 

is now

capitalize = utile.capitalize, 

prompt.js

The following needs to be changed from:

var events = require('events'),
    readline = require('readline'),
    utile = require('utile'),
    async = utile.async,
    capitalize = utile.inflect.capitalize, 
    read = require('read'),
    validate = require('revalidator').validate,
    winston = require('winston');

to:

var events = require('events'),
    readline = require('readline'),
    utile = require('utile'),
    async = utile.async,
    capitalize = utile.capitalize, 
    read = require('read'),
    validate = require('revalidator').validate,
    winston = require('winston');

configure & disable colors

I see that winston supports configurable colors. It would be nice if prompt did, too. Perhaps it could use the same code to do it if winston's color facility got reorganized a little bit.

Printing to Console Refresh Prompt Needed

It would be very nice to be able to still do console.log statements to stdout and the prompt would fix itself. Or at minimum have the ability to do prompt.reprompt() and whatever the current prompt, if there is one, is reprinted to stdout.

To make it full fledged goodness you would need to cache the characters typed at the current prompted, print X delete characters removing the old prompt and the cached thus far typed characters and then, after console.log...., reprompt the current prompt with cached content.

FYI - I have socket.io stuff and incoming data is printed out and that is breaking the prompts.

exit codes

could we get non-zero exit codes if a user exits out of a prompt?

i tried this, didn't work :(

process.on('exit', function () {
    process.exit(1);
});

What if there was invalid value in one of array items?

There seems no chance for user to go back and fix it.

?> numbers1 54
?> numbers2 a  <= INVALID VALUE
?> numbers3
-------------- { '0': '54' }
-------------- { '0': 'a' }
error:   Invalid input for numbers
?> numbers3 <= HOW TO FIX number2 ?

Prompt properties should adhere to JSON-Schema format

Currently prompt properties are contained in an array of objects with a name properties in each object.

JSON-Schema properties are stored as key-value pairs where the key is the name property and the value is an object which represents the specific property.

We should stick to the JSON-Schema format since we are already using it in resourceful and revalidator.

automatically call .start()?

The idea is to eliminate the need to call prompt.start().

In a closure containing prompt.start and prompt.get:
  var started = false;
in prompt.start:
     started = true;

in prompt.get:
     if (!started) prompt.start();

This could be implemented directly with extendFunction:

(function() {
  var started = false;
  extendFunction('prompt.start', function(){
    started = true;
  });
  extendFunction('prompt.get', function(){
    if (!started) prompt.start();
  });
})();

override property to bypass prompt.

Although prompting is a good UX for first time users, power users may prefer passing in all the options as cli arguments.

I propose adding prompt.override which could be used to achive this:

prompt.override = {name: 'whoever'}

prompt.get(['name'], function (err,answer){
   //it will just take name from .override and not prompt the user. 
})

Then it would be a one line change to add this feature to all the nodejitsu cli tools, prompt.override = optimist.argv

the option would still be validated, and would call back an error if it failed.

_

_

Nested conditional prompts?

I have been looking for a way to nest prompts, but have been unsuccessful:

prompt.get(['question'], function(err, results) {
    if (results.question.toLowerCase() === 'y' || 'yes') {
        prompt.get(['question2'], function(err, results){
            do something;
        })
    } else {
        process.emit('exit');
    }
});

When I run this, regardless of what value the question prompt returns, question2 gets asked.

I have been using prompt for a large portion of my script, so would like to incorporate it in this instance as well. Before I go off and write a replacement function, I wanted to see if somehting like this would be supported (and I am just missing it)

Thanks

Conditional prompt

There should be a way to do conditional prompt. Useful when some questions depends on the answer of others.

Prompt not blocking

on node v0.8.16 prompt is not blocking when using example code:

var prompt = require('prompt');

//
// Start the prompt
//
prompt.start();

//
// Get two properties from the user: username and email
//
prompt.get(['username', 'email'], function (err, result) {
//
// Log the results.
//
console.log('Command-line input received:');
console.log(' username: ' + result.username);
console.log(' email: ' + result.email);
});

Allow for falsy value options

When prompting the user for input, it should be possible to use a falsy value as an option, e.g. options.message to be the empty string, or options.colors to be false.

In addition, when options.message is the empty string, the delimiter should not be printed before the question.

read package dependency problem

$ npm install -d
npm info it worked if it ends with ok
npm info using [email protected]
npm info using [email protected]
npm info preinstall [email protected]
npm http GET https://registry.npmjs.org/vows
npm http GET https://registry.npmjs.org/pkginfo
npm http GET https://registry.npmjs.org/read
npm http GET https://registry.npmjs.org/revalidator
npm http GET https://registry.npmjs.org/utile
npm http GET https://registry.npmjs.org/winston
npm http 304 https://registry.npmjs.org/read

npm ERR! Error: No compatible version found: read@'>=1.0.0- <1.1.0-'
npm ERR! Valid install targets:
npm ERR! ["0.0.1","0.0.2","0.0.3","0.1.0","0.1.1"]
npm ERR! at installTargetsError (/usr/local/lib/node_modules/npm/lib/cache.js:496:10)
npm ERR! at next_ (/usr/local/lib/node_modules/npm/lib/cache.js:446:17)
npm ERR! at next (/usr/local/lib/node_modules/npm/lib/cache.js:423:44)
npm ERR! at /usr/local/lib/node_modules/npm/lib/cache.js:416:5
npm ERR! at saved (/usr/local/lib/node_modules/npm/lib/utils/npm-registry-client/get.js:151:7)
npm ERR! at Object.oncomplete (/usr/local/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:230:7)
npm ERR! You may report this log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR! [email protected]
npm ERR!
npm ERR! System Darwin 12.0.0
npm ERR! command "node" "/usr/local/bin/npm" "install" "-d"
npm ERR! cwd /Users/kimon/Documents/fourleafcl/temp/prompt/prompt
npm ERR! node -v v0.6.19
npm ERR! npm -v 1.1.24
npm ERR! message No compatible version found: read@'>=1.0.0- <1.1.0-'
npm ERR! message Valid install targets:
npm ERR! message ["0.0.1","0.0.2","0.0.3","0.1.0","0.1.1"]
npm http 304 https://registry.npmjs.org/utile
npm http 304 https://registry.npmjs.org/pkginfo
npm http 304 https://registry.npmjs.org/revalidator
npm http 304 https://registry.npmjs.org/winston
npm http 200 https://registry.npmjs.org/vows
npm http GET https://registry.npmjs.org/vows/-/vows-0.6.3.tgz
npm http 200 https://registry.npmjs.org/vows/-/vows-0.6.3.tgz
npm info shasum 5b4b2abd99ef1e6b224dc7c58031742f7288b02a
npm info shasum /var/folders/8h/hdz315fj0mdd96p8h5pwfpf00000gn/T/npm-1344029022746/1344029022746-0.9754867081064731/tmp.tgz
npm info shasum 5b4b2abd99ef1e6b224dc7c58031742f7288b02a
npm info shasum /Users/kimon/.npm/vows/0.6.3/package.tgz
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /Users/kimon/Documents/fourleafcl/temp/prompt/prompt/npm-debug.log
npm not ok
npm not ok

Including description and type: 'number' causes invalid input

Including both a type:'number' and description key seems to break the input.

var fields = {
  price : {
    description : 'Price',
    default : 10,
    type : 'number'
  }
};

prompt.get({ properties : fields }, function (err, result) { 
  // other stuff...
 });

Output:

prompt: Price:  (10) 
error:   Invalid input for Price
prompt: Price:  (10) 1
error:   Invalid input for Price

Using message instead fixes the problem, but doesn't give you a nice name in the input.

BUG: When I add validation to a prompt schema, the name is outputted instead of the description when prompting.

e.g. If I do this:

var promptProperties = [                                                                                                                                   
     {
         description: "Enter your username",
         name: 'username',
         validator: /^[a-zAZ0-9\._-]+$/,
         warning: 'Username must be only letters and/or numbers'
     },
     {
         description: "Enter your password",
         name: 'password',
         hidden: true
     },  
     {
         description: "Enter the message subject",
         name: 'subject'
     },  
     {
         description: "Enter the email message",
         name: 'message'
     }
];

then the first prompt shows prompt: username: but if I do

var promptProperties = [                                                                                                                                   
     {
         description: "Enter your username",
         name: 'username',
     },
     {
         description: "Enter your password",
         name: 'password',
         hidden: true
     },  
     {
         description: "Enter the message subject",
         name: 'subject'
     },  
     {
         description: "Enter the email message",
         name: 'message'
     }   
];

then the first prompt shows prompt: Enter your username: as expected.

Extraneous space prepended to delimiter

Hi,

See line 194 of prompt.js:

191  prompt.getInput = function (prop, callback) {
192    var name   = prop.message || prop.name || prop,
193        propName = prop.name || prop,
194        delim  = prompt.delimiter + ' ',
195        raw    = [prompt.message, delim + name.grey, delim.grey],
196        read   = prop.hidden ? prompt.readLineHidden : prompt.readLine,
197        length, msg;

If I set prompt.message and prompt.delimiter to '' (empty string) I would like the property message to begin in the first column of the terminal. As it stands, it will be indented by a single space.

The README states:

The basic structure of a prompt is this:
    prompt.message + prompt.delimiter + property.message + prompt.delimiter;

The default prompt.message is "prompt," the default prompt.delimiter is ": ", and 
the default property.message is property.name.

This isn't really the case. The default prompt.delimiter is ":" and you pad it with an additional space.

Thanks,
-John

prompt .toLowerCases property names.

This doesn't seem to work:

prompt.get([ 'hookName' ], function (err, results) {
  introspect.generate(results.hookName);
});

because instead of results having a .hookName property, it has a .hookname property.

Imo, it would be nice to fix this, but .toLowerCase-ing strikes me as a deliberate thing to do.

Chinese characters problem

var prompt = require('prompt');
prompt.start();

prompt.get(['中文'], function (err, result) {
console.log(' username: ' + result['中文']);
});

this works fine itself.
1

but when i use this snippet in my project,it comes across problem below:
2

the cursor goes in wrong position :(

Alternate name for "default" property?

Would it be possible to use an alternate name or create an alias for the "default" property? JSHint is reporting it as a reserved word when I try to lint my code (because it is a reserved word).

Bug: Default values not registering for Numbers in JSON-schema API

To replicate:

var prompt = require('../lib/prompt');

var schema = {
  properties: {
    cookies: {
      name: 'cookies',
      format: 'number',
      default: 10
    }
  }
};

prompt.start();
prompt.get(schema, function (err, result) {
  console.log(result);
});
prompt: cookies:  (10) 
[ENTER]

If user presses ENTER without typing value, 10 ( the default value ) is not picked up in the result.

cursor position error with multibyte string descriptions

schema:

schema =
    properties:
        'username':
            description: '用户名'
            pattern: /^[a-zA-Z\s\-]+$/
            message: '用户名必须由字母、空格、横线组成'
            required: true
        'password':
            description: '密码'
            required: true
            hidden: true

result:

prompt: 用户名d
prompt: 密码:
{ username: 'd', password: 'a' }

and i have another question:
How to remove the prefix of each line such as "prompt: " "error: ". or place them with other strings

提示: 
错误: 
...

"before" is ignored if description is present, and required flag + default value is uneffective (need to refactor regexp)

Hi guys prompt is a great module, but I've found a couple of minor issues:

var schema={
  properties:{
   filename: {
      before: function(value) { return 'v -> ' + value.red; },
//       description:'Enter output file name'.green,
      pattern: /\b|(^[a-zA-Z\s\-]+$)/,
      message: 'Name must be only letters, spaces, or dashes',
      default: 'filename.json',
      required: false
    },
  }
}

If description is uncommented, then the before function is ignored. Why?

pattern has to be \b|(actual pattern) to allow empty strings, as in (http://stackoverflow.com/questions/3333461/regular-expression-which-matches-a-pattern-or-is-an-empty-string). Otherwise required flag is ignored and an error message is prompted, ignoring the default value and asking for a valid string.

Using Node.js 0.8.15 on Ubuntu 12.04

No support for Array type in JSON-Schema implementation

Currently, there is no way enter valid values for arrays.

Example:

var prompt = require('../lib/prompt');

var schema = {
  properties: {
    flavors: {
      type: 'array'
    }
  }
};

prompt.start();
prompt.get(schema, function (err, result) {
  if(err) {
    console.log('cancelled error');
    return;
  }
  console.log(err, result);
});

Instead of not being able to enter any values, the user should be presented with a mini-menu for adding items to an array until they are done adding items.

Backspace key does not appear to register while 'hidden' is 'true'

While using Prompt's 'hidden' property to ask for password data, I noticed that hitting a wrong key and then hitting backspace did not allow me to correct my mistake on the fly - when I checked the data that Prompt returned, every letter key I pressed was present in the final string, as if backspace had never been pressed.

Support better port input validation (ie. functions)

related : nodejitsu/jitsu#18

Basically you have to jump through hoops right now if there is a list of properties being added to an object and you need to use a function (in this case a http request) to test if something is valid. In this case we should allow validator to be a simple function that matches :

function myValidator ( newValue, next ) {
  next( isValid( newValue ) );
}

Version management

Quick question....

Why in your package.json you used a fixed version. It should be better to use a ~ in the require, it helps to follow the latest module based on its minor version without any change on your module.

eg. ~0.6.2 instead of 0.6.2

See : https://github.com/isaacs/node-semver

My 2 cents

process.openStdin() cause problems in Windows

Using process.openStdin() cause some problems in windows, when prompting in a event loop queued callback. I first open this issue in flatiron/flatiron all the explanation is here.

The easy way to reproduce this problem is running something like this:

process.nextTick(function(){
    process.stdin.resume();
    process.stdin.setEncoding('utf8');
    process.stdin.on('error', function (err) {
        console.log(err);
        process.exit();
    });
    process.stdin.on('data', function (chunk) {
        process.stdout.write('data: ' + chunk);
    });
});

process.openStdin();
process.stdin.pause();

Prompt produces errors in conjunction with Cygwin

Running prompt on a Windows machine within the Cygwin environment produces the following error output. (I've reduced the test-case down to a 'simplest' example).

Node-prompt does run properly in the normal windows environment, but I'd like to use prompt along with some libraries that require cygwin-type support.
It does seem to be a prompt specific problem as other nodejs libraries I've used do not have the same problem (examples: http, express, optimist, socket.io)

Simple Example (prompt-test.js)

var prompt = require('prompt');
prompt.start();
prompt.get(['input'], function (err, result) {
    console.log('input: ' + result.input);
});

Output

prompt: input:
events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: read ENOTCONN
    at errnoException (net.js:884:11)
    at Socket._read (net.js:389:21)
    at Socket.Readable.read (_stream_readable.js:304:10)
    at Socket.read (net.js:291:43)
    at new Socket (net.js:185:10)
    at process.stdin (node.js:660:19)
    at EventEmitter.prompt.start (~\node_modules\prompt\lib\prompt.js:75:38)
    at Object.<anonymous> (\path\to\file\prompt-test.js:2:8)

Invalid cursor position after CTRL-C on mac os

Not sure if this is Mac OS specific or not.

To reproduce:

var prompt = require('../lib/prompt');

var schema = {
  properties: {
    cookies: {
      name: 'cookies',
      type: 'number',
      default: 0
    }
  }
};

prompt.start();
prompt.get(schema, function (err, result) {
  if(err) {
    console.log('cancelled error');
    return;
  }
  console.log(err, result);
});

**Run the script, and press CTRL-C when prompted ( to cancel prompt )

~/dev/flatiron/prompt/node examples/schema.js 
prompt: cookies:  cancelled error
~/dev/flatiron/prompt/

Notice that the console.log doesn't register as a new line? It's dumping it on the same line as the prompt. Canceling a prompt should jump the cursor to the start of the next line.

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.