Tuesday, 2 October 2018

node.js: readline: close event

Close event is emitted in one of the following conditions.
a.   When rl.close() method is called and the readline.Interface instance
b.   The input stream receives its 'end' event;
c.   The input stream receives <ctrl>-D to signal end-of-transmission (EOT);
d.   The input stream receives <ctrl>-C to signal SIGINT and there is no 'SIGINT' event listener registered on the readline.Interface instance

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

/* Add a callback function on readline.Interface instance close event */
rl.on('close', function(){
 console.log("Control over input and output streams is closed");
});

/* Ask a question to the user and print the received answer */
rl.question('What is your name? ', (answer) => {
  console.log(`Hello: ${answer}, How are you?`);
  rl.close();
});

Output
What is your name? Krishna
Hello: Krishna, How are you?
Control over input and output streams is closed



Previous                                                 Next                                                 Home

No comments:

Post a Comment