Cannot trigger 'end' event using CTRL D when reading from stdin

倾然丶 夕夏残阳落幕 提交于 2019-12-03 10:42:29

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!