简体   繁体   English

调试节点JS逻辑

[英]Debugging Node JS Logic

For simplicity's sake I shortened the node.js application. 为简单起见,我缩短了node.js应用程序。

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. 如上面的片段所示,它逐行读取以确定用户提交的电子邮件是否存在于Subscription.txt中。 Well I actually have about 7 copies of it and it changes the emailExist variable from false to true. 好吧,我实际上有大约7个副本,它会将emailExist变量从false更改为true。 However, it invokes the function that has it when it's set to false. 但是,当它设置为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事件处理程序中:

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. 原因是readline不等待终端输入。 Instead you pass it an event handler (your on('line') function) that it will call if there are incoming input. 相反,您将事件处理程序(您的on('line')函数)传递给它,如果有传入输入,它将调用该事件处理程序。 Note: readline is who will be calling the function. 注意:readline是谁将调用该函数。 You're just passing it to readline, not calling it. 您只是将其传递给readline,而不是调用它。 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"). 因此on里面的函数将在将来而不是现在被调用(这就是某些语言将这种类型的编程称为“ 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. 还有其他一些方法可以使代码更易于阅读,例如promise和async / await,但是在研究promise或async / await之前,请确保您了解异步代码的工作方式以及回调的含义,因为它们不会消除异步的性质。代码,只是使语法看起来有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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