简体   繁体   English

为什么node.js将错误视为回调中的第一个参数

[英]Why does node.js look for error as the first parameter in a callback

I have the following simple code.. however the "data" variable doesn't return the contents of input.txt. 我有以下简单的代码..但是,“数据”变量不会返回input.txt的内容。

var fs = require("fs");

fs.readFile('input.txt', function (data) {
     console.log(data.toString());
});

console.log("Program Ended");

The code below works because node.js reads the first parameter, err, and the input.txt contents come from the 2nd parameter 以下代码有效,因为node.js读取第一个参数err,而input.txt内容来自第二个参数

var fs = require("fs");

fs.readFile('input.txt', function (err, data) {
   if (err) return console.error(err);
   console.log(data.toString());
});

console.log("Program Ended");

Is this just a node.js thing to look for the error in the first parameter? 这仅仅是在第一个参数中查找错误的node.js东西吗? What if I did not want to check for an error in the callback function? 如果我不想在回调函数中检查错误怎么办?

It's convention to pass error as the first parameter to a callback function. 按照惯例,将错误作为第一个参数传递给回调函数。 It's first to prevent it from being ignored. 首先是防止它被忽略。 You don't have to check it, of course, but if there is an error it's likely that your data is bad or meaningless anyway. 当然,您不必检查它,但是如果出现错误,则您的data很可能已损坏或毫无意义。

The reason that fs.readFile('input.txt', function (data) { doesn't work is that the error is passed into your data variable, since it is the first parameter. What you actually name the parameters doesn't matter, the parameter order is decided by fs.readFile . fs.readFile('input.txt', function (data) {不起作用的原因是该错误已传递到您的data变量中,因为它是第一个参数。您实际上对这些参数的命名没有关系,参数顺序由fs.readFile决定。

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

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