【问题标题】:Node js - How to pause execution of subsequent lines of code while waiting for user input in node jsNode js - 如何在节点 js 中等待用户输入时暂停后续代码行的执行
【发布时间】:2016-06-27 19:13:57
【问题描述】:

我是 node.js 的新手,并且正在学习它。我编写了一个代码来提示来自 CLI 的用户输入超时。问题是,随后的代码行在等待用户输入时被执行并且没有暂停。我如何在节点中实现这一点。下面是我的代码

var readline = require('readline');

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

waitForUserInput = function (timeout) {
var timer = setTimeout(function () {
    console.log("Process Resumed..");
    rl.close();
}, timeout);

rl.question("Press Enter to Continue..!!", function () {
    console.log("Process Resumed..");
    clearTimeout(timer);
    rl.close();
});}

方法调用是

waitForUserInput(5000);

到目前为止,如果我执行 console.log("Hello");输出是

进程暂停。按 Enter 继续..!! 你好

我只需要用户输入或超时后的 console.log 消息。

【问题讨论】:

  • 你不能那样做。相反,请使用承诺。
  • 你能举个例子吗?

标签: javascript node.js user-input readline


【解决方案1】:

您不应该停止执行 Node.js 进程。 Node.js 构建在 EventLoop 之上。在 Node.js 中,您的代码应该异步工作 - 您要求用户进行键盘输入并注册一段代码,一旦用户完成输入就会触发该代码。

对于任何类型的命令行输入,我建议使用Inquirer.js package。您应该创建一个prompt 并在then 块中处理用户输入(then 在无错误地履行承诺时调用)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2014-01-27
    • 2021-02-05
    • 2021-08-22
    相关资源
    最近更新 更多