[英]Node js - How to pause execution of subsequent lines of code while waiting for user input in node js
我是node.js的新手並且在飛行中學習它。 我編寫了一個代碼來提示CLI的userinput超時。 問題是,在等待用戶輸入時,后續的代碼行被執行而不是暫停。 我如何在節點中實現這一點。 以下是我的代碼
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(“你好”); 輸出是
流程已暫停。 按Enter繼續.. !! 你好
我只想在用戶輸入或超時后才能獲得console.log消息。
您永遠不應該停止執行Node.js進程。 Node.js構建在EventLoop
。 在Node.js中,您的代碼應該異步工作 - 您要求用戶輸入鍵盤並注冊一段代碼,一旦用戶完成輸入就會觸發該代碼。
對於任何類型的命令行輸入,我建議使用Inquirer.js包 。 您應該創建一個prompt
並在then
塊中處理用戶輸入( then
在履行沒有錯誤的情況下調用)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.