调试节点JS逻辑

时间:2017-02-24 00:48:54

标签: javascript node.js

为简单起见,我缩短了node.js应用程序。

在我的服务器中,我复制了一段代码,试图弄清楚是什么问题。从逻辑上讲,它应该有效。

// 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.");
        });
    }
});

如上面的代码段所示,它逐行读取以确定用户提交的电子邮件是否存在于Subscription.txt中。好吧,我实际上有大约7个副本,它将emailExist变量从false更改为true。但是,当它设置为false时,它会调用具有它的函数。以下是我的控制台输出: Console Output

有关为何发生这种情况的任何想法?

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是您需要在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.");
        });
    }
});

原因是readline不等待来自终端的输入。相反,你传递一个事件处理程序(你的on('line')函数),如果有传入的输入,它将调用它。注意:readline是谁将调用该函数。您只是将其传递给readline,而不是将其传递给readline。因此,on中的函数将在未来调用,而不是现在(这是某些语言称之为此类编程的一个原因"期货")。

您可以通过将逻辑重构为函数来提高可读性(并减少回调地狱):

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);
});

还有其他方法可以使代码更好地读取,例如promises和async / await,但请确保在深入到promises或async / await之前了解异步代码的工作方式以及回调是什么,因为它们不会删除代码的异步性质,只使语法看起来不同。