Node.js - How to read user input from the console?

Asked

Viewed 22,669 times

8

In Java:

System.out.println("Diga algo: ");
Scanner leitor = new Scanner(System.in);
String resp = leitor.nextLine(); //ou nextInt, nextDouble, etc

In C++

cout << "Diga algo: ";
string name;
cin >> name;

How to read input from the console on Node.js?

2 answers

14


Using the module readline:

var readline = require('readline');
var resp = "";

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

leitor.question("Qual módulo pra ler dados no node.js?\n", function(answer) {
    var resp = answer;
    console.log("\nSua resposta '" + resp + "' foi grava com sucesso numa variável inútil");
    leitor.close();
});
  • 1

    For the example you have that just need to know the module to read data would probably be better to get this information through the program input arguments.

5

    
process.stdin.on('readable', ()=>{ 
  // reads what is being typed. 
  let variable = process.stdin.read(); 
  // trying to read 
  variable = variable.toString().replace(/\n/, ""); 
  variable = variable.replace(/\r/, ""); });

// Hope this helps

Browser other questions tagged

You are not signed in. Login or sign up in order to post.