Tuesday, 2 October 2018

node.js: readline: line event

line event is emitted, whenever the input stream receives an end-of-line input (\n, \r, or \r\n).

In case of standard input, this event is fired, when user press <Enter>, or <Return> keys.

Example
rl.on('line', (input) => {
  console.log(`Received: ${input}`);
});

Call back function receives the input provided by the user (or) stream.

Below application prompts the user to enter his/her hobbies.

HelloWorld.js
/* Variable to store user hobbies */
var hobbies = [];

/* 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
});

// Adding close and line events
/* Add a callback function on readline.Interface instance close event */
rl.on('close', function(){
 console.log("Your hobbies are %j", hobbies);
});

/* Ask a question to the user and print the received answer */
rl.on('line', (hobby) => {
 if(hobby.toLowerCase().trim() === 'exit'){
  rl.close();
 }else{
  hobbies.push(hobby);
  rl.setPrompt('Would you like to enter your hobby ?, or type "exit" to quit : ');
  rl.prompt();
 }
});

/* Prompt user for the hobby */
rl.setPrompt('Please enter your hobby : ');
rl.prompt();

Output

Please enter your hobby : Cricket
Would you like to enter your hobby ?, or type "exit" to quit : Hockey
Would you like to enter your hobby ?, or type "exit" to quit : Football
Would you like to enter your hobby ?, or type "exit" to quit : Chess
Would you like to enter your hobby ?, or type "exit" to quit : exit
Your hobbies are ["Cricket","Hockey","Football","Chess"]


Previous                                                 Next                                                 Home

No comments:

Post a Comment