I’m writing a node.js app, and I’m trying to read input from the console. For some reason though, it’s not following my switch case correctly. Here is what I have:
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
if(typeof chunk == "string")
console.log('This should be working!');
switch(chunk)
{
case '/quit':
console.log('Terminating Server...');
process.exit();
break;
case '/hi':
console.log('Hi Back!');
break;
default:
console.log('Command not found');
break;
}
});
No matter what I type, i always get “Command not found” and “This should be working!”. If the chunk is a string, why can’t I get the “Hi Back!” output when I type “/hi”?
The chunk will end with a linebreak (e.g. “
\n“), so just strip any trailing whitespace before switching: