pt2 stdin/stdout possible interview question

create a node app that is ran from the command-line, which will prompt the user to enter in a number for how many times the program will output hello world!

example:

> how many times would you like to say hello?
> 5
> // hello world!
> // hello world!
> // ...
var stdin = process.stdin, stdout = process.stdout;

function sayHello(times) {
  var i;
  for (i = 0; i < parseInt(times); i++) {
    stdout.write('hello world! \n');
  }
  process.exit();
}

stdin.resume();
stdin.setEncoding('utf8');

stdout.write('please enter in how many times you want to say hello... \n')

stdin.on('data', function(data) {
  data = parseInt(data);
  if (isNaN(data)) {
    stdout.write('please enter a number bro... \n');
  }
  else {
    sayHello(data);
  }
})
  1. assign process.stdin/stdout to vars
  2. we create a function that takes in (what we assume is) a number
  3. the function creates a for loop to write to stdout hello world however many times we pass into it.
  4. stdin.resume() initiates the cli to ask for input, then we set the encoding.
  5. we then ask the user how many times they want to say hello world
  6. we add an event handler onto stdin to call a callback once Enter is pressed.
  7. if what is entered is not a number(NaN), we write for them to enter a number. (extra: because we use .on(…) instead of .once(…) the event handler will run as many times as the user hits enter, whereas .once(…) would run only after 1 Enter)
  8. if the input is a number, we call our sayHello(data) function to output hello world! as many times as we asked it.
  9. sayHello() calls process.exit() at the end of its for look to exit the program.