node.jsreadlineconsole.readline

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


Solution

  • 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)