如何在Node.js中无限读取

栏目: Node.js · 发布时间: 7年前

内容简介:翻译自: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


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Little Typer

The Little Typer

Daniel P. Friedman、David Thrane Christiansen、Duane Bibby、Robert Harper、Conor Mcbride / MIT Press / 2018-10-16 / GBP 30.00

An introduction to dependent types, demonstrating the most beautiful aspects, one step at a time. A program's type describes its behavior. Dependent types are a first-class part of a language, and are......一起来看看 《The Little Typer》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试