Reading value from console, interactively
you can't do a "while(done)" loop because that would require blocking on input, something node.js doesn't like to do.
Instead set up a callback to be called each time something is entered:
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
console.log("you entered: [" +
d.toString().trim() + "]");
});
I've used another API for this purpose..
var readline = require('readline');
var rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('guess> ');
rl.prompt();
rl.on('line', function(line) {
if (line === "right") rl.close();
rl.prompt();
}).on('close',function(){
process.exit(0);
});
This allows to prompt in loop until the answer is right
. Also it gives nice little console.You can find the details @ http://nodejs.org/api/readline.html#readline_example_tiny_cli
I believe this deserves a modern async-await
answer, assuming node >= 7.x is used.
The answer still uses ReadLine::question
but wraps it so that the while (done) {}
is possible, which is something the OP asks about explicitely.
var cl = readln.createInterface( process.stdin, process.stdout );
var question = function(q) {
return new Promise( (res, rej) => {
cl.question( q, answer => {
res(answer);
})
});
};
and then an example usage
(async function main() {
var answer;
while ( answer != 'yes' ) {
answer = await question('Are you sure? ');
}
console.log( 'finally you are sure!');
})();
leads to following conversation
Are you sure? no
Are you sure? no
Are you sure? yes
finally you are sure!
Edit. In order to properly end the input, call
cl.close();
at the end of the script.
The Readline API has changed quite a bit since 12'. The doc's show a useful example to capture user input from a standard stream :
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
More information here.