【问题标题】:Node.js: readline never returnsNode.js:readline 永远不会返回
【发布时间】:2018-08-15 23:39:23
【问题描述】:

我尝试了几个不同版本的 node.js,但 readline.question 似乎从未执行我的回调。谁能发现我做错了什么?

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

rl.question('What do you think of node.js? ', function(answer) {
  console.log('Thank you for your valuable feedback:', answer);
  rl.close();
});

【问题讨论】:

    标签: node.js readline


    【解决方案1】:
    /*
     * main.js
     */
    //
    const readline = require('readline');
    //
    const rl = readline.createInterface({
    input: process.stdin,
    output:process.stdout
    });
    //
    var question = "What do you think of node.js? \n";
    var feedback = "Thank you for your valuable feedback:\n ";
    console.log(question);
    rl.question('//////////////...ANSWER..//////////////////////\n:',
    function(answer){
    console.log(feedback, answer);
    rl.close();
    });
    //
    /////////////////////////////////////////////////////////////////////
    //Your environment should be set up for using Node.js and npm.
    /////////////////////////////////////////////////////////////////////
    /////////////////...OUTPUT...////////////////////////////////////////
    //$ node main.js
    //What do you think of node.js?
    //
    //////////////...ANSWER...//////////////////////
    //: Cool. All APIs of Node.js are asynchronous.
    //Thank you for your valuable feedback:
    //  Cool. All APIs of Node.js are asynchronous.
    //
    ////////////////////////////////////////////////////////////////////
    //
    //
    

    【讨论】:

    • 嗨 BM3,在发布答案时,用几句话解释这个人做错了什么以及你做了什么来解决它会很有帮助。谢谢!
    • NodeJS 是 JavaScript。它使用事件驱动的非阻塞 I/O 模型。非阻塞模型的问题在于,回调函数可以运行到最后,而无需等待程序正常运行所需的其他关键信息。例如,如果程序要求用户输入,它应该在继续下一步之前等待用户的响应。程序员控制程序流程。他/她应该决定何时使用异步函数以及何时使用同步函数。程序员可以使用console.log("To test line by line output.")。
    【解决方案2】:

    代码完美运行,我的问题是由于我使用的是forever。使用foreverpm2 之类的流程管理器时,请注意您的流已被修改,因此底层流程可能无法接收输入。

    【讨论】:

      猜你喜欢
      • 2019-11-15
      • 2011-07-25
      • 1970-01-01
      • 2012-10-02
      • 2013-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多