简体   繁体   English

节点js - 如何在等待节点js中的用户输入时暂停后续代码行的执行

[英]Node js - How to pause execution of subsequent lines of code while waiting for user input in node js

I'm new to node.js and learning it on the fly. 我是node.js的新手并且在飞行中学习它。 I have written a code to prompt for userinput from CLI with timeout. 我编写了一个代码来提示CLI的userinput超时。 The problem is, the subsequent lines of code are executed and not paused while waiting for user input. 问题是,在等待用户输入时,后续的代码行被执行而不是暂停。 how do i achieve this in node. 我如何在节点中实现这一点。 Below is my code 以下是我的代码

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

Method Invocation is 方法调用是

waitForUserInput(5000);

As of now if i do a console.log("Hello"); 截至目前,如果我做一个console.log(“你好”); the output is 输出是

Process Paused. 流程已暂停。 Press Enter to Continue..!! 按Enter继续.. !! Hello 你好

I want the console.log message only after user input or timeout. 我只想在用户输入或超时后才能获得console.log消息。

You should never stop execution of a Node.js process. 您永远不应该停止执行Node.js进程。 Node.js is build on top of an EventLoop . Node.js构建在EventLoop In Node.js your code should work in asynchronously - you ask the user for keyboard input and register a piece of code that will be triggered once the the user finished the input. 在Node.js中,您的代码应该异步工作 - 您要求用户输入键盘并注册一段代码,一旦用户完成输入就会触发该代码。

For any kind of command line input I recommend using the Inquirer.js package . 对于任何类型的命令行输入,我建议使用Inquirer.js包 You should create a prompt and handle the user input in the then block ( then is called when a promise fulfilled without errors) 您应该创建一个prompt并在then块中处理用户输入( then在履行没有错误的情况下调用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM