anseki / readline-sync Goto Github PK
View Code? Open in Web Editor NEWSynchronous Readline for interactively running to have a conversation with the user via a console(TTY).
License: MIT License
Synchronous Readline for interactively running to have a conversation with the user via a console(TTY).
License: MIT License
It could be nice if Ctrl+C was allowed in keyInSelect
, when the cancel option is available. Pressing Ctrl+C should be interpreted as cancel.
Is it possible to use this as a browser module or does it exclusively rely on OS-specific TTY implementations for input?
Hi there,
When using hideEchoBack
, such as
var a = readlineSync.question("What's up?", { hideEchoBack: true });
the user can't press backspace to remove characters. Is this deliberately this way?
In Unix, you can typically delete characters when typing in a hidden password.
Thank you for the library and best wishes!
Under Windows 8.1 ANSI escape sequence contained in options.display strings are not parsed but instead are output as-is in the default cmd.exe terminal. I tracked it down to this line:
https://github.com/anseki/readline-sync/blob/master/lib/readline-sync.js#L171
By writing directly to the raw stdout file stream, parsing of ansi codes is circumvented, since this happens in the libuv layer which (which gets skipped). When I replace the line above with process.stdout.write(options.display);
ANSI sequences are properly parsed+evaluated.
Hi, your module doesn't work on Debian (and Honwhy reported a problem on CentOS too).
Error: The platform don't support interactively reading from stdin
I thought those distros would support interactive reading, I'm a bit disappointed…
Also, could you give us a list of supported platforms? Maybe we could start a wiki page?
Hello, It's me again. On win 7 I get this error, but on Win 10 all ok.
C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:66
if (res.error) { throw res.error; }
^
/*
Error: The platform doesn't support interactive reading
at readlineExt (C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:268:19)
at tryExt (C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:65:15)
at C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:164:15
at _readlineSync (C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:224:5)
at getValidLine (C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:724:11)
at exports.question (C:\hardsub_avisynth\tools\js_scripts\node_modules\readline-sync\lib\readline-sync.js:800:10)
at Object.<anonymous> (C:\hardsub_avisynth\tools\js_scripts\psp_encoder.js:130:12)
at Module._compile (module.js:430:26)
at Object.Module._extensions..js (module.js:448:10)
at Module.load (module.js:355:32)
*/
I am unable to kill the process (by pressing Ctrl+C or Ctrl+Z) when inside a call to either keyInYN
or keyInYNStrict
. Regular question calls work as expected, but I would think you would also want to let the user kill the process even in a call to keyInYNStrict
. Or perhaps, this could be an option at least?
I think it would be a quite useful little addition to have the possibility to set a default value for a question. So if the user just hits enter, that default value is being used instead of an empty string or whatever it currently is.
What do you think?
I've been unable to figure out exactly why, but for some reason hitting ^C
to exit readlineSync.question()
will result in the process hanging forever.
This is the code it takes to reproduce.
var readline = require('readline-sync');
process.on('SIGSEGV', function() {
console.log('hi');
});
readline.question('Hit ^C to exit (this will then hang forever)');
Repo for this here: https://github.com/thejameskyle/__readline-sync-test
Found this while using the signal-exit
module as a sub-dependency.
Is there a way to timeout the prompt/question thrown by readline-sync if no user input is detected for a certain period of time?
Hello! This is my first "issue" xD so sorry if I get wrong in something.
First, I want to say: great job! This package is very useful.
Secondly, I wonder if something could be added so the developer could specify a value which could be already typed as answer once the question is thrown to the user. Like the "defaultInput" option, but another one, like "initialInputTyped", or something similar. This way, the developer can freely adapt the prompt's initial value, at the same time that the question is being made, to more specific purposes. But at the same time, also letting the final user remove it partially or totally.
Thank you anyway, great tool!!
tried the code snippet in the example but with this additional option the text was still there
I use gitlab-ci and run in docker container debian:jessie from offical repo
Take the following code:
var readlineSync = require('readline-sync');
...
var answer = readlineSync.question('What is your name? ');
console.log('Hi ' + answer + '!');
Running node v0.10.28 on OS X 10.9.3.
Any thoughts?
Edit: Also upgraded Node to latest and tested on node v0.10.29. Same result.
Script runs without errors until I try to run the debugger then immediately throws error:
enter command: bash: line 1: 10155 Segmentation fault node --nocrankshaft --nolazy --nodead_code_elimination --debug-brk=15454 '/home/ubuntu/workspace/305CDE/02 Objects and Functions/shopping/index.js'
Process exited with code: 139
Unfortunately I have an issue on a Windows machine using node v5.10.1.
When asking the user the first question, the answer will sometimes only be accepted after pressing ⏎ once, then answering and (if required) pressing ⏎ again.
Taken from the examples:
'use strict';
const readlineSync = require('readline-sync');
var userName = readlineSync.question('May I have your name? :');
console.log('Hi ' + userName + '!');
With limited input possibilities I can often times write anything I want when prompted for the first time, then I press ⏎ and only then my input is filtered regarding the possible options.
'use strict';
for (let i = 1; i <= 3; i++) {
if (readlineSync.keyInYNStrict('What about ' + i + '?')) {
console.log('yep');
} else {
console.log('nope');
}
}
Any further answers are accepted correctly.
Without further investigation I assume this is related to the Windows terminal but unfortunately I am limited to this requirement.
Can anyone else confirm this issue, provide a simple workaround or fix the cause?
Hello
I've a problem with the lib, wait I call :
var out = readlineSync.question(question,{noEchoBack: true})
console.log("you are : "+out)
9
10 (show a prompt again I don't know why)
you are : 10
Can you please help me for this ?
Thanks man ! Nice project by the way !!
It seems keyInPause does nothing if enter key is pressed.
By default, any key is accepted. You can change this behavior by specifying limit option (e.g. accept only a Space Bar).
Thank you!
There does not appear to currently be a way to distinguish between end-of-file (e.g. Ctrl-D on Linux) and an empty line. I suggest returning a null when EOF is encountered.
running readline-sync 1.2.21 on node 0.12.7 on OS X Yosemite.
If I run something that calls e.g. question() from the REPL, I get no echo while typing. In the regular node REPL, my echoed response shows up all at once after pressing the return key. In the coffee REPL, it never gets echoed at all.
D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:269
extMessage = e.stderr.trim();
^
TypeError: Cannot read property 'trim' of undefined
at readlineExt (D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:269:28)
at tryExt (D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:65:15)
at D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:166:15
at _readlineSync (D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:226:5)
at getValidLine (D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:726:11)
at Object.exports.question (D:\web\resourcerefresher\node_modules\readline-sync\lib\readline-sync.js:802:10)
at getFiles (D:\web\resourcerefresher\refresh.js:21:29)
at ReadStream.<anonymous> (D:\web\resourcerefresher\refresh.js:8:31)
at emitOne (events.js:77:13)
at ReadStream.emit (events.js:169:7)
It's sad when error handling code causes errors.
OS: Mac OS X Yosemite (10.10.5)
NodeJS: 5.2.0 installed with homebrew
readline-sync: 1.2.22
var rl = require('readline-sync');
console.log(rl.question("Enter password: ", {hideEchoBack: true}));
Enter some text (123456) and hit backspace a couple times. No mask characters are erased (*) and the result is still 123456.
Awesome project.
If the script is prompting using readline-sync, how does one exist the script? Ctrl+C doesn't seem to be working.
Thanks!
var readlineSync = require('readline-sync'),
chalk = require('chalk'),
user, pw, command;
readlineSync.setPrint(function(display, encoding) {
logger.log(chalk.stripColor(display)); // Remove control characters.
});
console.log(chalk.black.bold.bgYellow(' Your Account '));
user = readlineSync.question(chalk.gray.underline(' USER NAME ') + ' :');
pw = readlineSync.question(chalk.gray.underline(' PASSWORD ') + ' :', {noEchoBack: true});
// Authorization ...
console.log(chalk.green('Welcome, ' + user + '!'));
readlineSync.setPrompt(chalk.red.bold('> '));
command = readlineSync.prompt();
/Users/Arvo/github/test/test.readlineSync.js:6
logger.log(chalk.stripColor(display)); // Remove control characters.
^
ReferenceError: logger is not defined
at /Users/Arvo/github/test/test.readlineSync.js:6:3
at _readlineSync (/Users/Arvo/github/test/node_modules/readline-sync/lib/readline-sync.js:116:7)
at Object.exports.question (/Users/Arvo/github/test/node_modules/readline-sync/lib/readline-sync.js:380:10)
at Object.<anonymous> (/Users/Arvo/github/test/test.readlineSync.js:10:21)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
what is logger?
need require('logger')?
I noticed that keyIn does not react when I hit the enter
key. Is there an option to allow this to be entered as a character?
It appears that the default limit is []
and keepWhitespace does not apply.
Fantastic library by the way thanks a lot.
I want create a tools to request server by conversation with the user via a console.
but found request is canot be send until the loop completed.
code like this
server
//main.js
var http = require("http");
var i=0;
http.createServer(function(request, response) {
console.log('request received' + i );
response.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
response.write(i.toString());
response.end();
i++;
}).listen(9990);
console.log('server started');
client
// readline.js
// npm install readline-sync
// npm install request
var readline = require("readline-sync");
var request = require("request");
for (var i = 0; i < 10; i++) {
var ans = readline.question("do requ ?");
if (ans == "y") {
console.log("begin to request");
request("http://localhost:9990", function (err, resp, body) {
console.log("get ->" + body);
});
}
}
exe processing:
left is server , right is client
The first four cycles , the server output nothing.
untill ten times , server output all things.
i have two question
thanks very much
Hi, thanks for making this great library. 😄
I recently ran into a problem while using Git for Windows (which uses the MSYS2/MinTTY shell if I recall correctly) to run my Node.js script. For some reason, when I run this code in that shell, which uses question
:
var rl = require('readline-sync');
function loginUser() {
console.log('Please enter your GitHub credentials.');
username = rl.question('Username: ');
password = rl.question('Password: ', { hideEchoBack: true }); // don't echo for password
saveCredentials(username, password);
}
then nothing actually happens. Instead of printing Username:
and then waiting for input, it looks like it just hangs there and won't respond no matter how many times Enter is pressed. When you finally Ctrl + C out of the process, it will flush out all of the input you had typed as if they were commands.
The repro script for this can be found here: https://github.com/jamesqo/git-delete
And yes, I tested and it seems to be working fine with regular old CMD.
Hi, according with these closed issues #27 #17 I'd say this issue persist, and maybe the explanation of the #17 is right, but if it does; why we would erase the normal content (not hidden) with the backspace key? And if we are planning to change a password, what happens if I make a mistake? Do I have to repeat the whole process? Take this as an example:
I think this module is really awesome because in some way, I remember the C# Console.ReadLine()
I'll appreciate this issue gets solved.
Thanks.
I'm developing a simple shell. Because I wanted the execution of code to be synced, input is managed through readline-sync. However, I've found that trying to do anything (including ^C or ^D) is useless. For example, a very basic code like:
rl = require('readline-sync');
input = rl.prompt();
keeps reading without ever responding. The same happens with other commands like rl.question
. I can only guess that V8 is unable to receive any input, for some reason.
I'm running a manually compiled node.js 0.10.35 on Ubuntu 14.04 LTS, using Bash and the GNOME Terminal.
I have to display a huge list of directories so that the user can choose from one of them. What is the reason for the limit of 35?
Using chalk together with readlineSync.question() does not change the color. I have the following code:
let name = readlineSync.question(chalk.red('Your name: '));
Which produces the following result on Windows command line:
←[31mYour name: ←[39m
I use the following system environment:
I get this error on windows 7x64.
If you resize the terminal window when prompting the user for input it throws 'Segmentation fault: 11'
ANSI escape codes (e.g., ^[[A^[[B^[[C^[[D
) show up in the output when user input is being acquired using [email protected]
Here's a screenshot of the behavior when using [email protected]
, where the sequence "up, down, right, left" was recorded as an input of "[A[B[C[D"
:
Here's a test script that exhibits the behavior:
console.log('You typed: ' + require('readline-sync').question('Type here: '));
Expected behavior I think is for left and right keys to move the caret and up/down arrows to flip through the input history (if enabled). I tested in several terminal emulators on OS X 10.9 with the same results.
Currently, the keyInSelect function displays a list of options for the user to choose from and an optional additional option labeled "CANCEL". While I know that you can enable and disable showing the "CANCEL" option, I'd like to see an option to customize the text displayed for that additional option to something other than "CANCEL". Currently, the way I'm using the readline-sync keyInSelect function is that I'm displaying a list of options that the user can toggle on and off. Every time the user selects a menu option the state of that option is toggled and the menu is re-displayed, allowing the user to toggle other options. Once the user is done toggling the options they want to choose, then they press "0" to select the "CANCEL" option, which commits their selected options and continues the program. It works very well for my use case, except for the fact that the word "CANCEL" is very confusing to users. For my program, I'd like to be able to change the word "CANCEL" to something like "DONE", or "CONFIRM". The actual functionality would be exactly the same as it is now, I just want to be able to override the default text of "CANCEL" to something else. Is it possible for you to add this feature?
Hello,
it would be great if there would be an option to output the defaultInput in the 'answer area', e.g.:
Your name? john doe▮
The user would not only see what his input will be, but he could also modify it before pressing Enter.
thanks for the nice package,
yours monsterkodi
script
var rl = require('readline-sync');
var secret = rl.question('Enter secret: ', { hideEchoBack: true });
console.log(secret);
Type a [backspace] b
output is ab.
Can you tell me if i am missing something?
When using keyInSelect
, is it possible to remove the CANCEL option entirely?
Where do we stand: so far it's not possible to properly read or write utf8-encoded cyrillic letters to older Windows terminals (even Win10 one with classic mode enabled) - results being garbage. While I was able to monkey patch this issue using iconv-lite, it's not like hacks could ever make a proper solution.
Just try some cyrillics in those code without my fixes:
var rl = require('readline-sync');
var user_name = rl.question("Как вас зовут ? ");
console.log("Hello, " + user_name + " !");
What could be done: I guess, some internal translation proc could be used for older Windows systems, probably one from iconv-lite mentioned above.
When I'm using Intellij Idea to run my node script,I got some error below:
node_modules/readline-sync/lib/read.sh: line 49: /dev/tty: Device not configured
Error: The platform doesn't support interactive reading
stty: /dev/tty: Device not configured
my code is simple:
"use strict"
let readlineSync = require("readline-sync");
let username = "";
while(username == ""){
username = readlineSync.question('username:');
}
This error won't happen when I'm using terminal to run node test.js.
But When I'm using idea IDE run,the error occured.
It will be ok when using nodejs native read-line when using Idea.
Under version v0.10.11 of node on linux OS the example code return the following error:
fs.js:476
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EAGAIN, resource temporarily unavailable
at Object.fs.readSync (fs.js:476:19)
at _readlineSync (/tmp/test/node_modules/readline-sync/lib/readline-sync.js:25:22)
at Object.exports.question (/tmp/test/node_modules/readline-sync/lib/readline-sync.js:51:10)
at Object. (/tmp/test/test.js:2:27)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
Thanks so much for the package! It's incredibly useful!
Is it possible to display the defaultInput to the user so that they can edit it as opposed to needing to type a brand new value?
For example:
readlineSync.question('Please edit value: ', {defaultInput: 'DEFAULT_VALUE'})
Please edit value: DEFAULT_VALUE
My use case is as follows:
Inputs have a maximum length. If value.length > max then I want to prompt the user to shorten the input without having to retype the entire value.
const rls = require('readline-sync')
console.log('你好')
rls.question('你好')
results
λ node test.js
你好
浣犲ソ
I'm on I'm on windows 7, node 6.2.1.
Don't work properly with iojs v2.3.2+.
When run it's make two request from user (only when use function first time?):
With text ask, but ignored input parameters.
Without text ask, but don't ignore parameters.
Test case from sample.
var readlineSync = require('readline-sync');
// Wait for user's response.
var userName = readlineSync.question('May I have your name? :');
console.log('Hi ' + userName + '!');
// Handle the secret text (e.g. password).
var favFood = readlineSync.question('What is your favorite food? :', {
hideEchoBack: true // The typed text on screen is hidden by `*` (default).
});
console.log('Oh, ' + userName + ' loves ' + favFood + '!');
I have a child process created by child_process.exec(), and the main process needs to query the child on stdin. The parent needs to read the response synchronously, which comes back on stdout.
Could you add a way to re-assign pipes (including stdio[3] and above preferably) as options?
Got this when running a cli app installed to home directory.
> child_process.js:1362
throw err;
^
Error: Command failed: /bin/sh -c "/home/rainevi/node_modules/ez-jenkins/node_modules/readline-sync/lib/read.sh"
/bin/sh: /home/rainevi/node_modules/ez-jenkins/node_modules/readline-sync/lib/read.sh: Permission denied
at checkExecSyncError (child_process.js:1339:13)
at Object.execFileSync (child_process.js:1359:13)
at _readlineShell (/home/rainevi/node_modules/ez-jenkins/node_modules/readline-sync/lib/readline-sync.js:103:29)
at _readlineSync (/home/rainevi/node_modules/ez-jenkins/node_modules/readline-sync/lib/readline-sync.js:58:19)
at Object.exports.prompt (/home/rainevi/node_modules/ez-jenkins/node_modules/readline-sync/lib/readline-sync.js:208:10)
at module.exports (/home/rainevi/node_modules/ez-jenkins/lib/cli/setup.js:10:25)
at Object.<anonymous> (/home/rainevi/node_modules/ez-jenkins/lib/cli/index.js:32:23)
at Object.<anonymous> (/home/rainevi/node_modules/ez-jenkins/lib/cli/index.js:34:4)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
System:
Linux version 2.6.32-431.20.3.el6.x86_64 ([email protected]) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC) ) #1 SMP Thu Jun 19 21:14:45 UTC 2014
It starts working if you chmod +x
the script.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.