Tuesday, 2 October 2018

node.js: Readline: rl.prompt([preserveCursor])

rl.prompt([preserveCursor])
rl.prompt prompt the user with information. rl.prompt() will resume the input stream if it has been paused.

HelloWorld.js
/* Import readline module */
var readline = require('readline');

/*
 * create a new readline.Interface instance that reads data from standard input
 * and write data to standard output
 */
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.on('line', (data) => {
 console.log(`Hello ${data}, How are you`);
 rl.close();
});

rl.setPrompt("Please Enter your name");
rl.prompt();


Output

Please Enter your nameKrishna

Hello Krishna, How are you

Prompt method takes a boolean argument, preserveCursor If it is set to true, then it prevents the cursor placement from being reset to 0.

HelloWorld.js

/* Import readline module */
var readline = require('readline');

/*
 * create a new readline.Interface instance that reads data from standard input
 * and write data to standard output
 */
var rl = readline.createInterface({
 input : process.stdin,
 output : process.stdout
});

var i = 0;
var count = 100;

/* Time is set to 200 milliseconds */
var seconds_to_wait = 0.2 * 1000;

function sleep_for_200_millis() {
 var waitTill = new Date(new Date().getTime() + seconds_to_wait);
 while (waitTill > new Date()) {
 }
}

while (i <= count) {
 sleep_for_200_millis();
 rl.setPrompt(`Value of i is is ${i}`);
 rl.prompt(true);
 i++;
}

rl.close();

Run the above application, you can observe message is displayed in same line.




Previous                                                 Next                                                 Home

No comments:

Post a Comment