Reputation: 646
I am writing nodejs code for Hackerearth test. I am pressing enter key but the process.stdin.on('end',function(){}) is not getting called. So I want to know when this 'end' event will get called? Or Can I use any other library for user input on Hackerearth. I have also views multiple question on stackoverflow for same but didn't get answer.
process.stdin.resume();
process.stdin.setEncoding("utf-8");
var input = '';
process.stdin.on("data", function (n) {
input += n;
});
process.stdin.on("end",function(){
console.log(input)
})
Upvotes: 0
Views: 1512
Reputation: 46
The end event is called when Node.js process is about to exit. Usually, you would expect this to happen when you press CRL+C or CRL+D. But CRL+C interrupts the process, so Node can't print anything in the console no more. If you are on Windows machine CRL+D is not supported by the interface so nothing will happen. See the issue here
So what you can do is to use the readline module. The close event will be triggered when you press either CRL+D or CRL+C.
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let input = '';
rl.on('line', (inputString) => {
input += inputString;
});
rl.on('close', () => {
console.log(input);
});
Upvotes: 1
Reputation: 1399
The callback of process.stdin.on("data"
is called when a 'return' is pressed (EOL=end of line) and you will get the text of the entered line.
The callback of process.stdin.on("end"
is called when the end of input (EOF=end of file) is reached. For an interactive console this is when you press ^D under Linux/MacOS (ctrl-D : 'ctrl'-key + 'D'-key). I think on Windows this might need to press ^Z (ctrl-Z) instead of ^D.
Depending on your needs, you have to use the "data" event handler to do your work instead of using the "end" event handler. What is the criteria to start your input processing? When it is not the reading of EOF or EOL, then you need to check that criteria in the "data" handler.
After EOL has been read, the script automatically ends. It is unclear to me if this is what you want.
Upvotes: 2