等待来自readline模块(Node.Js)的用户输入

时间:2018-12-30 20:17:57

标签: javascript node.js node-modules readline

我正在创建一个模块,以获取经验并缩短一些代码。我有一段代码以简化的方式使用readline,例如Transforms。 Readline不会等待答案。它产生了这个:

  

你几岁?未定义

代码:

var x = arkin.question("How old are you? ");

我这样称呼它:

const readline = require('readline');

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

exports.question = function(q){

  var response;

  rl.setPrompt(q);
  rl.prompt();
  rl.on('line', (userInput) => {
    response = userInput;
    rl.close();
  });

  rl.on('close', () => {
    return response;
  });
}

我尝试使用此代码:

var age = arkin.question("How old are you? ");
console.log(age);

但是我得到了相同的结果。预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

无论何时调用arki.question,它都会注册事件监听器.on(“ line”)和.on(“ close”),然后从函数返回。从.on(“ close”)事件监听器question函数返回的内容都不知道,因为它不再位于调用堆栈中。您可以使用回调或将async...await与Promise一起获得结果。

带有回调

const readline = require('readline');

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

exports.question = function(q , cb ){

    var response;

    rl.setPrompt(q);
    rl.prompt();

    rl.on('line', (userInput) => {
        response = userInput;
        rl.close();
    });

    rl.on('close', () => {
        return cb(response);
    });
};

您这样称呼

var age  = arki.question("how old are you? ", resp => {
    console.log(resp);
});

有诺言

const readline = require('readline');

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

exports.question = function(q){

    var response;

    rl.setPrompt(q);
    rl.prompt();

    return new Promise(( resolve , reject) => {

        rl.on('line', (userInput) => {
            response = userInput;
            rl.close();
        });

        rl.on('close', () => {
            resolve(response);
        });

    });


};

您这样称呼

arki.question("how old are you? ").then( response => console.log(response) );

; ( async () => {
    console.log(await arki.question("how old are you? "));
})();