When I'm trying to compare a string with an input from process.stdin.on , I'm getting false always.
//Imagine user inputting 'hello' always.
process.stdin.on('data', userInput => {
let text = userInput.toString();
if(text == 'hello'){
console.log("True");
}
if(text === 'hello'){
console.log("True");
}
process.exit();
});
If I check typeof userInput it shows string. If i log userInput it shows exact the same as my string.
so, why these conditions are false?
CodePudding user response:
The user input includes the end-of-line markers, for example "\r\n"
in Windows (but this might be "\n"
on other systems). So you must check whether text === "hello\r\n"
.
Alternatively, you can let readline
split the user input into lines for you:
readline.createInterface({input: process.stdin})
.on("line", text => {
if(text === 'hello')
console.log("True");
});
CodePudding user response:
Another alternative , you could use openStdin with a listener
const stdin = process.openStdin();
stdin.addListener("data", function(d) {
const text = d.toString().trim();
console.log("you entered: [" d.toString().trim() "]");
if (text == 'hello') {
console.log("True");
}
if (text === 'hello') {
console.log("True");
}
});