DeepakBilikere DeepakBilikere - 2 months ago 7
Javascript Question

Issue in accepting dynamic input from the terminal in nodejs using process.stdin

I have been working since a long time on this issue and did surf a lot of sites but did not find a convincing answer.
Let me explain my requirement. I want to accept inputs from the terminal, use those inputs to run a set of instructions and then again accept new set of inputs from the terminal using

process.stdin
in nodejs.

Please find below my sample code. Kindly throw light on my mistakes and a better way to put the instructions, this would help me learn better.

input();
console.log("Completed 1");
input();
function input()
{
process.stdin.setEncoding('utf8');
process.stdin.resume();
process.stdin.on('data',function(text){
console.log("Type: " + typeof text);
if(text == "quit"){
console.log("Inside if");
done();
}
console.log("Received: " + text);
});
}

function done(){
console.log("Exiting");
process.exit();
}


When I run this code, if my input is "quit", this text is not being matched and doesn't enter the if condition. It continues to accept anything and everything.

Answer

The string you entered has a new line character at the end:

quit\n

Providing that in your conditional will fix this issue. See this documentation as example.

input();
console.log("Completed 1");
input();
function input()
{
    process.stdin.setEncoding('utf8');
    process.stdin.resume();
    process.stdin.on('data',function(text){
        console.log("Type: " + typeof text);
        if(text === "quit\n"){
            console.log("Inside if");
            done();
        }
        console.log("Received: " + text);
    });
}

function done(){
    console.log("Exiting");
    process.exit();
}

Edit: To address your second concern, see the documentation for process. The solution is clear. Hand a call back to the 'exit' event. Only synchronous code is allowed in that callback.

function input() {
    process.stdin.setEncoding('utf8');
    process.stdin.resume();
    process.stdin.on('data',function(text){
        console.log("Type: " + typeof text);
        if(text === "quit\n"){
            console.log("Inside if");
            done();
        }
        console.log("Received: " + text);
    });
    process.on('exit', (code) => {
        console.log('got to it');
    }); }
Comments