内容简介:翻译自:https://stackoverflow.com/questions/24464404/how-to-readline-infinitely-in-node-js
while(1){
rl.question("Command: ",function(answer){
console.log(answer);
})
}
刚刚尝试了这段代码,但是逐个输入,它会使“Command:”行闪烁.我知道node.js是非阻塞的,但我不知道如何解决这个问题.
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
关键是不要使用同步循环.我们应该在处理答案后才问下一个问题.递归是要走的路.我们定义函数,询问问题并处理答案,然后在答案处理后从内部调用它.这种方式我们从头开始,就像常规循环一样.但循环不关心ansyc代码,而我们的实现关心.
翻译自:https://stackoverflow.com/questions/24464404/how-to-readline-infinitely-in-node-js
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Text Processing in Python
David Mertz / Addison-Wesley Professional / 2003-6-12 / USD 54.99
Text Processing in Python describes techniques for manipulation of text using the Python programming language. At the broadest level, text processing is simply taking textual information and doing som......一起来看看 《Text Processing in Python》 这本书的介绍吧!