Coder Social home page Coder Social logo

prompt-sync's Introduction

SYNOPSIS

A sync prompt for node. very simple. no C++ bindings and no bash scripts.

Works on Linux, OS X and Windows.

BASIC MODE

var prompt = require('prompt-sync')();
//
// get input from the user.
//
var n = prompt('How many more times? ');

WITH HISTORY

History is an optional extra, to use simply install the history plugin.

npm install --save prompt-sync-history
var prompt = require('prompt-sync')({
  history: require('prompt-sync-history')() //open history file
});
//get some user input
var input = prompt()
prompt.history.save() //save history back to file

See the prompt-sync-history module for options, or fork it for customized behaviour.

API

require('prompt-sync')(config) => prompt

Returns an instance of the prompt function. Takes config option with the following possible properties

sigint: Default is false. A ^C may be pressed during the input process to abort the text entry. If sigint it false, prompt returns null. If sigint is true the ^C will be handled in the traditional way: as a SIGINT signal causing process to exit with code 130.

eot: Default is false. A ^D pressed as the first character of an input line causes prompt-sync to echo exit and exit the process with code 0.

autocomplete: A completer function that will be called when user enters TAB to allow for autocomplete. It takes a string as an argument an returns an array of strings that are possible matches for completion. An empty array is returned if there are no matches.

history: Takes an object that supplies a "history interface", see prompt-sync-history for an example.

prompt(ask, value, opts)

ask is the label of the prompt, value is the default value in absence of a response.

The opts argument can also be in the first or second parameter position.

Opts can have the following properties

echo: Default is '*'. If set the password will be masked with the specified character. For hidden input, set echo to '' (or use prompt.hide).

autocomplete: Overrides the instance autocomplete function to allow for custom autocompletion of a particular prompt.

value: Same as the value parameter, the default value for the prompt. If opts is in the third position, this property will not overwrite the value parameter.

ask: Sames as the value parameter. The prompt label. If opts is not in the first position, the ask parameter will not be overridden by this property.

prompt.hide(ask)

Convenience method for creating a standard hidden password prompt, this is the same as prompt(ask, {echo: ''})

LINE EDITING

Line editing is enabled in the non-hidden mode. (use up/down arrows for history and backspace and left/right arrows for editing)

History is not set when using hidden mode.

EXAMPLES

  //basic:
  console.log(require('prompt-sync')()('tell me something about yourself: '))

  var prompt = require('prompt-sync')({
    history: require('prompt-sync-history')(),
    autocomplete: complete(['hello1234', 'he', 'hello', 'hello12', 'hello123456']),
    sigint: false
  });

  var value = 'frank';
  var name = prompt('enter name: ', value);
  console.log('enter echo * password');
  var pw = prompt({echo: '*'});
  var pwb = prompt('enter hidden password (or don\'t): ', {echo: '', value: '*pwb default*'})
  var pwc = prompt.hide('enter another hidden password: ')
  var autocompleteTest = prompt('custom autocomplete: ', {
    autocomplete: complete(['bye1234', 'by', 'bye12', 'bye123456'])
  });

  prompt.history.save();

  console.log('\nName: %s\nPassword *: %s\nHidden password: %s\nAnother Hidden password: %s', name, pw, pwb, pwc);
  console.log('autocomplete2: ', autocompleteTest);

  function complete(commands) {
    return function (str) {
      var i;
      var ret = [];
      for (i=0; i< commands.length; i++) {
        if (commands[i].indexOf(str) == 0)
          ret.push(commands[i]);
      }
      return ret;
    };
  };

prompt-sync's People

Contributors

davidmarkclements avatar gfranco93 avatar hans-strudle avatar heapwolf avatar insin avatar navbruce avatar stefanyohansson avatar thegiddylimit avatar yegodz 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

prompt-sync's Issues

Segmentation fault error on zsh

Hi there!

Coming from Nucleus, one of the users reported a problem with our init script.

While prompting for user input, the script terminates with a seg-fault if the user tries to resize the terminal window.

[1] 3380 segmentation fault nucleus init

I know that this could be a problem with zsh, since the error seems to be on a quite low level.

Steps to reproduce:

  • Open a terminal window with zsh (I tested this on MacOS with iTerm and zsh) and navigate to the prompt-sync repository root.
  • Run node test.js and resize the window during the first prompt.

Autocomplete error

Code:
import prompt from 'prompt-sync';

var gender = prompt('Are you a male or a female? (M - male, F - female)');

if(gender == 'M' || gender == 'F'){
console.log(gender);
} else {
console.log('Try again!');
}

Error:

var autocomplete = config.autocomplete =
^

TypeError: Cannot create property 'autocomplete' on string 'Are you a male or a female? (M - male, F - female)'

Wrong cursor position with history and colored label

Hi,

I have a problem when I use a colored label (with \u001b[* characters) and I navigate throw history.
On UP there is no problem, but on DOWN, cursor is at a wrong place.

I see that UP and DOWN have different code to display label and history and I don't know why.

So, I don't know if you should modify line 114 to be identical to line 99:

@@ -111,7 +111,7 @@ function create(config) {
               str = history.next();
               insert = str.length;
             }
-            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G');
+            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str);
             break;
           case '\u001b[D': //left arrow
             if (masked) break;

or if you should clean ask variable:

@@ -58,6 +58,7 @@ function create(config) {
       value = opts.value;
     }
     ask = ask || '';
+    var rawAsk = ask.replace(/\u001b\[(?:\d+;)\d+[a-zA-Z]/g, '');
     var echo = opts.echo;
     var masked = 'echo' in opts;
     autocomplete = opts.autocomplete || autocomplete;
@@ -111,7 +112,7 @@ function create(config) {
               str = history.next();
               insert = str.length;
             }
-            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G');
+            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+rawAsk.length+1)+'G');
             break;
           case '\u001b[D': //left arrow
             if (masked) break;

or another solution I didn't see.

UTF8 emoji space issue

Try something like this:

prompt('A wild ๐Ÿข appears.');

Output:

A wild ๐Ÿขappears.

Note the spacing. I might look into fixing this bug but that depends on if this library is dead or not. For instance, there's a few open PRs that haven't been answered in months.

Thanks!

unexitable when run in loop

I have the following simple coffeescript file:

# test.coffee
ps = require("prompt-sync")()
out = NaN
while isNaN out
  out = parseInt ps("enter input")

When I run this using coffee test.coffee and instead of entering text try exiting with control+c, it does not exit but just goes to the next tick of the while loop. When I enter "1", it exits as expected.

There's also the same behavior in Javascript. Here is the same script compiled to JS:

// test.js
// Generated by CoffeeScript 2.0.3
(function() {
  var out, ps;

  ps = require("prompt-sync")();

  out = 0/0;

  while (isNaN(out)) {
    out = parseInt(ps("enter input"));
  }

}).call(this);

When running this with node test.js, the same behavior occurs.

Is this expected, or should we be manually handling control+c?

  • prompt sync version '4.1.5'
  • coffee version 2.0.3
  • node version 9.0.0

fails in node 0.10 on OS X

this is due to reading from /dev/stdin

/usr/bin/tty will output the current tty e.g. /dev/ttys006 - this can be used instead,
but spawning /usr/bin/tty has to be done async on node 0.10 - which means there
would be an async setup step.

$ node --version
v0.10.40
$ node -e "require('prompt-sync').prompt()"

fs.js:488
  var r = binding.read(fd, buffer, offset, length, position);
                  ^
Error: EAGAIN, resource temporarily unavailable
    at Object.fs.readSync (fs.js:488:19)
    at Object.prompt (/Users/davidclements/z/nearForm/fuge/fuge/node_modules/prompt-sync/index.js:54:15)
    at [eval]:1:24
    at Object.<anonymous> ([eval]-wrapper:6:22)
    at Module._compile (module.js:456:26)
    at evalScript (node.js:565:25)
    at startup (node.js:80:7)
    at node.js:935:3

ENOENT: no such file or directory, open 'D:\dev\stdin'

Filename:
fs.js:549
  return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open 'D:\dev\stdin'
    at Error (native)
    at Object.fs.openSync (fs.js:549:18)
    at Object.prompt (D:\web\resourcerefresher\node_modules\prompt-sync\index.js:37:15)
    at Object.prompt.question (D:\web\resourcerefresher\refresh.js:15:15)
    at getFiles (D:\web\resourcerefresher\refresh.js:25:23)
    at ReadStream.<anonymous> (D:\web\resourcerefresher\refresh.js:7:31)
    at emitOne (events.js:77:13)
    at ReadStream.emit (events.js:169:7)
    at readableAddChunk (_stream_readable.js:146:16)
    at ReadStream.Readable.push (_stream_readable.js:110:10)

Seems to be lacking any windows support.

Minor update

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

Copy Paste not working properly

When i'm trying to copy/paste an input, it returns a strange value.

In my pc it works normally, but in my VM i can't paste anything.
I'm using Windows

I tried to paste the string "Some value" and i got it:
image

OBS: The paste works normally when using CMD/PowerShell without opening my EXE in it

Sample code fails if used within a class method, presumably because 'prompt' is a reserved word

When I install and attempt to use prompt-sync, the basic sample code works if run all by itself, but if

var prompt = require('prompt-sync')();

is put at the top of a JavaScript class file (global scope) and then

var n = prompt('How many more times? ');

Is put inside a class method defined in that file (where it should have access to the variable), it crashes claiming that 'prompt' isn't defined. If I change the definition to use 'prompt2', things work. So you should probably avoid using 'prompt' as a variable as it's a JS reserved word.

Cannot access key listeners while prompt is in use

I would like to check for key listeners but every solution I have found on the internet, while I am awaiting a response for the prompt I can not check for keys.

I'd like to add a feature so when a user presses the Up/Down keys on the keyboard it'll go through the history of entered prompt values.

Any thoughts?

Unable to input non-English letters on Windows

Hi.

I cannot input any non-English letter during prompt. Outside the program I can type whatever letter I want so it doesn't seem to be a problem with my terminal.

I'm running on Windows 10 with node v14.15.0 and using prompt-sync 4.2.0.

A minimal code example which can reproduce the issue:

const prompt = require('prompt-sync')();
console.log(prompt(`Type non-English letter: `));
// I am unable to type any non-English letter

Assertion failed: (fd > STDERR_FILENO)

When doing if (null === prompt.prompt({ask: 'foo?'})) process.exit(0), I get:

Assertion failed: (fd > STDERR_FILENO), function uv__close, file ../deps/uv/src/unix/core.c, line 487.

Pressing Tab multiple times does not cycle through the values of the autocomplete function

Don't know if this is a bug, but it is not what I expected.

My code uses a prompt with an autocomplete function. After entering some text, pressing Tab shows the first result that this function returns.

Press Tab again and the result is not the second result from this list. Instead, the second item from the unfiltered list is shown.

I noticed the autocomplete function is called twice when pressing Tab for the second time. The first time the selection contains the result returned when handling the first Tab and once with an empty parameter.

v4 proposal

@0x00A - thoughs?

  • move history into its own module
  • simplify api
var prompt = require('prompt-sync')({
  history: require('prompt-sync-history')(historyFilename, maxHistory),
  autocomplete: myAutocompleteFn,
  sigint: false
});
var ask = 'icecream?';
var value = 'yes';

var answer = prompt(ask, value);

var pw1 = prompt('pw?', {
  value: 'password1',
  echo: '*'
});

var pw2 = prompt('pw2?', {echo: ''}); 

var pw3 = prompt.hide('pw3'); //shorthand for pw2

Doesn't work with nodemon

Steps to reproduce

app.js

console.log(require('prompt-sync')()('Enter anything: '));

To run:

nodemon app.js

This app doesn't exit.

Expected output:

Enter anything: a
a
[nodemon] clean exit - waiting for changes before restart

Actual output:

Enter anything: a
Enter anything: a
                   b
Enter anything: a
b
                      c
Enter anything: a
b
c

But running directly in node works correctly:

node app.js
  • Winver: Window 10 20H2 OS Build 19042.1237
  • nodemon --version 2.0.7
  • node --version v14.15.4

Index.js is break

The index file there are an illegal expression assigned a one variable on the method create( );

line:24: var autocomplete = config.autocomplete = config.autocomplete || function(){return []};

That issue throw a TypeError:
terminal

Will not work in Bash command when information piped in

To recreate, create the following file prompt-test.js, as a very simple test:

#!/usr/bin/env node
const prompt = require("prompt-sync")({"sigint": true})

for (var i = 0; i < 5; i++) {
  console.log("Before prompt line")
  var result = prompt("This is a test -- enter something >");
  console.log("Result of prompt", result)
}

If run as ./prompt-test.js, it will ask for an input 5 times and print that output as you might expect.

However if you trying running echo hello world | ./prompt-test.js, the prompt itself is caught in a loop and repeats the prompt line and all previous inputs continually.

This might be happening because of my lack of understanding about Bash processes, sub-processes, or piping. Any help appreciated.

process.stdin.setRawMode is not a function

events.js:160
throw er; // Unhandled 'error' event
^

TypeError: process.stdin.setRawMode is not a function
at prompt (C:\Git\LiveTranslate\node_modules\prompt-sync\index.js:66:34)

This can be fixed by ignoring setRawMode for non-TTY consoles

TypeError: Cannot create property 'autocomplete' on string

Code:

    config.token = prompt('No token is set! Please create your bot at discordapi.com and paste the token here (see (git page) for more help with this): ')

result:

C:\Users\(username)\Documents\(project name)\node_modules\prompt-sync\index.js:20
  var autocomplete = config.autocomplete =
                                         ^

TypeError: Cannot create property 'autocomplete' on string 'No token is set! Please create your bot at discordapi.com and paste the token here (see (github URL) for more help with this): '
    at create (C:\Users\(username)\Documents\(project name)\node_modules\prompt-sync\index.js:20:42)
    at Object.<anonymous> (C:\Users\(username)\Documents\\index.js:33:20)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Function.Module.runMain (module.js:676:10)
    at startup (bootstrap_node.js:187:16)
    at bootstrap_node.js:608:3

Prompt repeating on Input

Whenever inputting a response into the prompt, it repeats the prompt. I have tried everything in my code to get try and it get it to not repeat, but it has not be a fruitful attempt so far. I was wondering if this was a feature of the package or a bug, if it is a feature would there be anyway to disable it?

False positive in < 0.12 Node.js version check with 4.x and 5.x

For !win32, this version check presumes a 0.x version of Node.js and will give false positives on 4.x and 5.x.

  var fd = process.platform !== 'win32' && +process.version.substr(3) < 12 ? 
    fs.openSync('/dev/tty', 'rs') : 
    process.stdin.fd;

Potential alternative:

Number(/v(\d+\.\d+)/.exec(process.version)[1]) < 0.12

cant paste properly

on osx, I am trying to paste a password. Only the last character of seems to get set. I have tried in both a hide and regular prompt.

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.