thehme
thehme

Reputation: 2886

Node.js program does not stop reading from stdin

I'm trying to read user input from stdin, in my case, two inputs entered on separate lines. However, when I run the following code (node program.js), it allows me to enter the first value, then I click enter and type in the second value, but when I click enter, it does not run the rest of my program. How do I tell it to stop reading and proceed?

process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
    input += chunk;
});

process.stdin.on("end", function () {  
    lines = input.split("\n");
    var numVals = lines[0];
    process.stdout.write(numVals + "\n");
    var vals = lines[1];
    process.stdout.write(vals+"\n");
});

Upvotes: 4

Views: 4804

Answers (1)

gregnr
gregnr

Reputation: 1272

Readable Streams expect an EOT (End of transmission) character before it triggers an "end" event. In bash this can be done using CTRL+D. If you want to explicitly stop after 2 line breaks, try this:

process.stdin.resume();
process.stdin.setEncoding("ascii");

var input = "";

process.stdin.on("data", function (chunk) {

    input += chunk;

    var lines = input.split("\n");

    //If there have been 2 line breaks
    if (lines.length > 2) {

        //Stop reading input
        process.stdin.pause();

        //Process data
        var numVals = lines[0];
        process.stdout.write(numVals + "\n");

        var vals = lines[1];
        process.stdout.write(vals+"\n");
    }
});

You are re-inventing the wheel a bit though. Line input is typically handled using the readline or prompt modules.

Upvotes: 3

Related Questions