4

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");
});
1
  • Added process.on('SIGINT', function(){ console.log('Got SIGINT. Press Control-D to exit.'); }); and now I can stop it with Ctrl+C followed by Ctrl+D, but it prints D Commented Mar 31, 2015 at 1:42

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I actually took pieces from the api site. I added the SIGINT and I can Ctrl+C, followed by Ctrl+D and the rest of my script runs. I will try your recommendation though because the above edit actually makes it print D for some reason.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.