[英]Debugging Node JS Logic
为简单起见,我缩短了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时,它将调用具有它的函数。 以下是我的控制台输出: 控制台输出
为什么会这样呢?
最简单的解决方案是您需要将所有内容移到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,而不是调用它。 因此on
里面的函数将在将来而不是现在被调用(这就是某些语言将这种类型的编程称为“ Futures”的原因)。
通过将逻辑重构为函数,可以稍微提高可读性(并减少回调地狱):
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);
});
还有其他一些方法可以使代码更易于阅读,例如promise和async / await,但是在研究promise或async / await之前,请确保您了解异步代码的工作方式以及回调的含义,因为它们不会消除异步的性质。代码,只是使语法看起来有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.