heapwolf/prompt-sync

Minor update

yegodz opened this issue · 3 comments

Thanks for a simple solution to a common need!!

I am using your code with some modifications ... please update it if you think it is an improvement.
I changed it from recursive to a while loop --- just better to use loops unless there is a good reason to recurse.
Also added an option to select hidden vs normal input and set echoing of '*' during hidden input

// attributed to: 
// https://github.com/hij1nx/prompt-sync


var fs = require('fs');

/**
 * prompt -- sync function for reading user input from stdin
 * @param   {Object} option {
 *                        hidden: If true, user input will not be echoed,
 *                        echo: set to a character to be echoed, default is '*'. Use '' for no echo
 *                        }
 * @returns {string} Returns the string input or null if user terminates with a ^C
 */

module.exports = function(option) {

  var term;
  var hidden = false;

  if (option && option.hidden) {
    term = '\u000D';
    hidden = true;
    if (!option.hasOwnProperty('echo'))
      option.echo = '*';
  }
  else 
    term = '\n';

  var fd = fs.openSync('/dev/stdin', 'rs');
  if (hidden) 
    process.stdin.setRawMode(true);
  var buf = new Buffer(1);
  var str = '';

  while (true) {
    fs.readSync(fd, buf, 0, 1);
    var ch = buf.toString();
    if (ch.charCodeAt(0) == 3){ // catch a ^C and return null
      process.stdout.write('^C\n');
      fs.closeSync(fd);
      process.stdin.setRawMode(false);
      return null;
    }
    if (ch == term) {
      fs.closeSync(fd);
      break;
    }
    else {
      str += ch;
      if (hidden) {
        process.stdout.write("\033[2K\033[200D" +  Array(str.length+1).join(option.echo));
      }
    }    
  }

  if (hidden) {
    console.log('');
    process.stdin.setRawMode(false);
  }
  return str;
}

if (require.main === module){
    var prompt = module.exports;
    console.log('enter name');
    var name = prompt();
    console.log('enter echo * password');
    var pw = prompt({hidden:true});
    console.log('enter no echo password');
    var pwb = prompt({hidden:true, echo: ''});  
    console.log('Name: %s, Password *: %s, Password no echo: ', name, pw, pwb);
}

oh! this is cool! would you consider doing a PR to integrate some of your ideas?

sure!
Give me a couple of days and I will send a PR

On Mar 17, 2015, at 9:54 AM, paolo fragomeni notifications@github.com wrote:

oh! this is cool! would you consider doing a PR to integrate some of your ideas?


Reply to this email directly or view it on GitHub #2 (comment).

we've since started using a while loop - thanks @yegodz - closing