简体   繁体   中英

Debugging Node JS Logic

For simplicity's sake I shortened the node.js application.

In my server I have copied a snippet of the code to try and figure out what's wrong. Logically speaking it's supposed to work.

// Subscribed to email service
app.get('/subscribe', function(req, res) {
    var emailExist = false;
    // Email to add
    var from = req.query.from;
    // Iterate through file and check to see if the email given exist or not.

    var readFile = fs.createReadStream("./Database/Subscription.txt");

    var readline = rl.createInterface({
        input: readFile,
        terminal: false,
    });

    readline.on('line', function(line) {
        if (line == from) {
            emailExist = true;
            console.log(line + " " + emailExist);
        }
    });

    console.log("hello " + emailExist);

    // If email dosn't exist
    if (emailExist === false) {
        console.log("I am false and need to be created");

        fs.appendFile("./Database/Subscription.txt", from + "\n", function(err) {
            if (err) {
                return console.log(err);
            }
            console.log(from + " was added to the email subscription.");
        });
    }
});

As shown in the snippet above, it reads line by line to determine if the email the user submit exists in Subscription.txt. Well I actually have about 7 copies of it and it changes the emailExist variable from false to true. However, it invokes the function that has it when it's set to false. Below is my console output: Console Output

Any thoughts as to why this is happening?

Simplest solution is you need to move everything inside the readline event handler:

readline.on('line', function(line) {
    if (line == from) {
        emailExist = true;
        console.log(line + " " + emailExist);
    }


    console.log("hello " + emailExist);

    // If email dosn't exist
    if (emailExist === false) {
        console.log("I am false and need to be created");

        fs.appendFile("./Database/Subscription.txt", from + "\n", function(err) {
            if (err) {
                return console.log(err);
            }
            console.log(from + " was added to the email subscription.");
        });
    }
});

The reason for this is that readline does not wait for input from the terminal. Instead you pass it an event handler (your on('line') function) that it will call if there are incoming input. Note: readline is who will be calling the function. You're just passing it to readline, not calling it. So the function inside the on will be called in the future, not now (that's one reason some languages call this type of programming "Futures").

You can improve readability a bit (and reduce callback hell) by refactoring the logic into a function:

function processEmail (exist, callback) {
    console.log("hello " + exist);

    // If email dosn't exist
    if (exist === false) {
        console.log("I am false and need to be created");

        fs.appendFile("./Database/Subscription.txt", from + "\n", function(err) {
            if (err) {
                if (callback) callback(err);
            }
            else {
                console.log(from + " was added to the email subscription.");
                callback(null);
            }
        });
    }
}

readline.on('line', function(line) {
    if (line == from) {
        emailExist = true;
        console.log(line + " " + emailExist);
    }

    processEmail(emailExist);
});

There are other ways to make the code nicer to read like promises and async/await but be sure you understand how asynchronous code work and what callbacks are all about before delving into promises or async/await because they don't remove the asynchronous nature of the code, only make the syntax look different.

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