Cannot trigger 'end' event using CTRL D when reading from stdin
If you are doing it in context to Hackerrank codepair tool then this is for you.
The way tool works is that you have to enter some input in the Stdin section and then click on Run which will take you to stdout.
All the lines of input entered in the stdin will be processed by the process.stdin.on("data",function(){}) part of the code and as soon as the input "ends" it will go straight to the process.stdin.on("end", function(){}) part where we can do the processing and use process.stdout.write("") to output the result on the Stdout.
process.stdin.resume();
process.stdin.setEncoding("ascii");
var input = "";
process.stdin.on("data", function (chunk) {
// This is where we should take the inputs and make them ready.
input += (chunk+"\n");
// This function will stop running as soon as we are done with the input in the Stdin
});
process.stdin.on("end", function () {
// When we reach here, we are done with inputting things according to our wish.
// Now, we can do the processing on the input and create a result.
process.stdout.write(input);
});
You can check the flow by pasting he above code on the code window.
I'd change this (key combo Ctrl+D
):
process.stdin.on('end', function() {
process.stdout.write('end');
});
To this (key combo Ctrl+C
):
process.on('SIGINT', function(){
process.stdout.write('\n end \n');
process.exit();
});
Further resources: process docs
I too came upon this problem and found the answer here: Github issue
The readline interface that is provided by windows itself (e.g. the one that you are using now) does not support ^D. If you want more unix-y behaviour, use the readline built-in module and set stdin to raw mode. This will make node interpret raw keypresses and ^D will work. See http://nodejs.org/api/readline.html.
If you are on Windows, the readline interface does not support ^D by default. You will need to change that per the linked instructions.
Alternatively
- Use an input file containing your test data for e.g. input.txt
- Pipe your input.txt to node
cat input.txt | node main.js