I'm new to node.js and learning it on the fly. I have written a code to prompt for userinput from CLI with timeout. 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"); the output is
Process Paused. Press Enter to Continue..!! Hello
I want the console.log message only after user input or timeout.
You should never stop execution of a Node.js process. Node.js is build on top of an 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.
For any kind of command line input I recommend using the Inquirer.js package . You should create a prompt
and handle the user input in the then
block ( then
is called when a promise fulfilled without errors)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.