while(1){
rl.question("Command: ",function(answer){
console.log(answer);
})
}
Just tried this code, but instead get input one by one, it blink the "Command: " line. I know node.js is non-blocking but i don't know how to fix this problems.
createReadStream('your/file'); var outstream = new stream; var rl = readline. createInterface(instream, outstream); rl. on('line', function(line) { // process line here }); rl. on('close', function() { // do something on finish here });
Method 1: Using the Readline Module: Readline is a native module of Node. js, it was developed specifically for reading the content line by line from any readable stream. It can be used to read data from the command line. const readline = require('readline');
The method createInterface() takes two parameters – the input stream and output stream – to create a readline interface. The third parameter is used for autocompletion and is mostly initialized as NULL .
var readline = require('readline');
var log = console.log;
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
var recursiveAsyncReadLine = function () {
rl.question('Command: ', function (answer) {
if (answer == 'exit') //we need some base case, for recursion
return rl.close(); //closing RL and returning from function.
log('Got it! Your answer was: "', answer, '"');
recursiveAsyncReadLine(); //Calling this function again to ask new question
});
};
recursiveAsyncReadLine(); //we have to actually start our recursion somehow
The key is to not to use synchronous loops. We should ask next rl.question
only after handling answer. Recursion is the way to go. We define function that asks the question and handles the answer and then call it from inside itself after answer handling. This way we starting all over, just like with regular loop. But loops don't care about ansyc code, while our implementation cares.
Another option, via the Node.js documentation, is to use events:
var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('OHAI> ');
rl.prompt();
rl.on('line', function(line) {
switch(line.trim()) {
case 'hello':
console.log('world!');
break;
default:
console.log('Say what? I might have heard `' + line.trim() + '`');
break;
}
rl.prompt();
}).on('close', function() {
console.log('Have a great day!');
process.exit(0);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With