Javascript 调试节点JS逻辑
为了简单起见,我缩短了node.js应用程序 在我的服务器中,我复制了一段代码,试图找出问题所在。从逻辑上讲,它应该是有效的Javascript 调试节点JS逻辑,javascript,node.js,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 ch
// 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不等待来自终端的输入。相反,您向它传递一个事件处理程序(您的('line')函数上的),如果有传入的输入,它将调用该事件处理程序。注意:readline是调用函数的用户。您只是将其传递给readline,而不是调用它。因此
上的中的函数将在将来调用,而不是现在(这是一些语言称这种编程类型为“未来”的原因之一)
通过将逻辑重构为函数,可以稍微提高可读性(并减少回调地狱):
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);
});
还有其他方法可以使代码更易于阅读,如Promissions和async/await,但在深入研究Promissions或async/await之前,请确保您了解异步代码的工作原理以及回调的全部内容,因为它们不会删除代码的异步性质,只会使语法看起来有所不同。安装chrome。在终端中:节点--inspect--debug--debug brk path/to/script.js
读取javascript中的异步回调,特别是在涉及readline的地方。在主逻辑完成后,您的readline联机回调正在发生。