Получение пользовательского ввода с помощью Javascript

Краткий обзор, прежде чем мы начнем с пользовательского ввода. Массивы хранят список значений и позволяют сохранять код чистым и читабельным. Вместо использования нескольких имен переменных с разными значениями использование массива позволяет использовать несколько значений, хранящихся в одной переменной. Каждое значение отделяется запятой, но с данными, показанными ниже, мы хотим объединить строку с помощью строкового оператора +.

var greeting = [
'Hello' +
'My name is Mary' +
'Have a nice day!'];
var answer = greeting
console.log(answer)

Вот код

var questions = [
  'Hello, How are you?',
  'What is your name?',
  'What is your favorite color?'];
// store our answers in an empty array
  var answer = [];
// now we need a function that will allow us to ask a question, function index will ask all the questions
  function ask(i) {
    process.stdout.write(`${questions[i]}`);
    process.stdout.write(" > ")
  }
// when the user types data in terminal and hits enter the callback function will execute and the data that was sent to the application will come in as a n argument. We are using node asynchronoulsy. This will not stop the terminal compared to earlier where the stdout stopped on terminal. It is being handled with an asynchronus callback.
  process.stdin.on('data', function(data) {
    // we will echo the data back by writing it to the terminal
  process.stdout.write('\n' + data.toString().trim() + '\n');
});
ask(0);

Наш код работает, и мы можем ввести ответ, но мы получаем (он повторяет данные) данные, которые мы печатаем обратно, теперь мы хотим, чтобы приложение распечатывало весь массив с каждым вопросом, чтобы мы могли ввести ответ.

var questions = [
  'Hello, How are you?',
  'What is your name?',
  'What is your favorite color?'];
// store our answers in an empty array
  var answer = [];
// now we need a function that will allow us to ask a question, function index will ask all the questions
  function ask(i) {
    process.stdout.write(`${questions[i]}`);
    process.stdout.write(" > ")
  }
// when the user types data in terminal and hits enter the callback function will execute and the data that was sent to the application will come in as a n argument. We are using node asynchronoulsy. This will not stop the terminal compared to earlier where the stdout stopped on terminal. It is being handled with an asynchronus callback.
  process.stdin.on('data', function(data) {
// answers.push will push an item into the array, you've filled otu an answer and hit enter. Now we push it to the answers array at the top which is empty
  answer.push(data.toString().trim());
// we want to add logic to see if there are any more questions
  // if there are more answers than questions, ask the following question
  if(answer.length < questions.length) {
    ask(answer.length);
  } else {
      process.exit();
  }
});
ask(0);

После того, как мы введем все вопросы, мы вернемся к приглашению терминала, потому что был вызван process.exit.