Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

console input not correct?

console input not correct?

Problem

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"?

Problem courtesy of: LordZardeck

Solution

The chunk will end with a linebreak (e.g. "\n"), so just strip any trailing whitespace before switching:

process.stdin.on('data', function (chunk) {
  chunk = chunk.replace(/\s+$/, '');
  switch (chunk) {
    case '/quit':
      // ...
Solution courtesy of: maerics

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

console input not correct?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×