In the following code
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function(chunk) {
process.stdout.write('data: ' + chunk);
});
process.stdin.on('end', function() {
process.stdout.write('end');
});
i can't trigger the 'end' event using ctrl+D, and ctrl+C just exit without triggering it.
hello
data: hello
data
data: data
foo
data: foo
^F
data: ♠
^N
data: ♫
^D
data: ♦
^D^D
data: ♦♦
I'd change this:
process.stdin.on('end', function() {
process.stdout.write('end');
});
To this:
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.
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.