Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

191
Visualizações
How to take user input in node js?

I'm trying to write tic-tac-toe game logic, so I need to take user inputs alternatively from user 'X and user 'O. The first player is chosen by a random function.

const prompt = require('prompt-sync')({ sigint: true });

const ticTacToe = {
    board: new Array(9).fill(null),
    person: null,
    player: function () {
        let number = Math.floor(Math.random() * 2);

        if (number === 0) {
            return this.person = 'X';
        }
        else {
            return this.person = 'O';
        }
    },

    start: function () {
        let firstPlayer = this.person;
        let count = 0;
        while (count <= 9) {
            let input;
            if (count === 0) {
                input = prompt(firstPlayer + ": ");
                count = count + 1;
            }
            else {

                let nextPerson = this.nextPlayer();
                input = prompt(nextPerson + ": ");
                count = count + 1;
            }
        }

    },
    nextPlayer: function () {
        let next;
        if (this.person === 'X') {
            return next = 'O';

        }
        else {
            return next = 'X';
        }
    }


}


The prompt is not changing and it is not terminating when count reaches 9. The output looks like-

X: 7
X: 7
      5
X: 7
5
         0
X: 7
5
0
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Below solution worked for me:

node --version
v10.19.0
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function readLineAsync(message) {
  return new Promise((resolve, reject) => {
    rl.question(message, (answer) => {
      resolve(answer);
    });
  });
} 

// Leverages Node.js' awesome async/await functionality
async function demoSynchronousPrompt() {
  var promptInput = await readLineAsync("Give me some input >");
  console.log("Won't be executed until promptInput is received", promptInput);
  rl.close();
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda