zorro47
zorro47

Reputation: 221

How to input data through console in node.js?

Although similar questions have already appeared, following theirs instructions I obtain an error. So my code is as follows

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

    var name;
    readline.question(`What's your name?`, (name))
        readline.close()

and as a result I have

{ RequestError: Syntax error, permission violation, or other nonspecific error
at StreamEvents.req.once.err

Do you know what is wrong? I'm using npm readline package

Upvotes: 1

Views: 1665

Answers (2)

SahilMak
SahilMak

Reputation: 148

According to the documentation, the second argument should be a callback function. What you currently have is an uninitialized variable. To fix it, you could do something like this:

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

const response = function (name) {
    console.log('Hello ' + name);
};
readline.question(`What's your name?`, response(name));
readline.close();

(I'm using const instead of var to adhere to ES6 standards for JavaScript/Node)

Upvotes: 2

gkont
gkont

Reputation: 199

The second argument of question should be a callback function

readline.question('What\'s your name',(name)=>{
    console.log(name)
});

Upvotes: 1

Related Questions