简体   繁体   中英

Node.js if statement not working as expected

I am learning javascript & Node.js. For some reason this IF statement is not working as I would've expected...
I cannot figure out how to solve this...

My code:

process.stdin.setEncoding('utf8');                      //Set UTF charcode

process.stdin.on('readable', () => {                    //Event fires when there's input
    var readConsole = process.stdin.read();             //Receive the input from console

    if(readConsole != null) {
        readConsole.trim().replace(/\r?\n|\r/g, " ");   //Trim input and remove line breaks

        process.stdout.write('Input: ' + readConsole);  //Output the input

        if(readConsole == "quit") {
            process.exit();
        }
    }
});

But for some reason, whenever I type "quit" in the console, it does not respond.

Here is an image of the problem:

在此处输入图片说明

Both trim() and replace() return a new string, but you are not assigning that value to any variable. You probably want to remove extra characters, not replace them with spaces (thanks @fvgs). Try:

readConsole = readConsole.trim().replace(/\r?\n|\r/g, "");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM