从控制台以交互方式读取值 [英] Reading value from console, interactively

查看:84
本文介绍了从控制台以交互方式读取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做一个带有控制台扩展的简单服务器http服务器.我找到了要从命令行数据读取的代码段.

  var i = rl.createInterface(process.stdin, process.stdout, null);
  i.question('Write your name: ', function(answer) {
    console.log('Nice to meet you> ' + answer);
    i.close();
    process.stdin.destroy();

  });

反复问这个问题,我不能简单地使用while(done) { }循环吗?如果服务器在询问时间接收到输出,也将破坏线路.

解决方案

您不能执行"while(done)"循环,因为这将需要阻止输入,而node.js则不愿意这样做. /p>

相反,设置每次输入内容时都要调用的回调:

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 thought to make an simple server http server with some console extension. I found the snippet to read from command line data.

  var i = rl.createInterface(process.stdin, process.stdout, null);
  i.question('Write your name: ', function(answer) {
    console.log('Nice to meet you> ' + answer);
    i.close();
    process.stdin.destroy();

  });

well to ask the questions repeatedly, i cant simply use the while(done) { } loop? Also well if the server receives output at the question time, it ruins the line.

解决方案

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() + "]");
  });

这篇关于从控制台以交互方式读取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆