問題描述
回調參數名稱 (Callback parameters name)
在這個簡單的node.js代碼中
var fs = require("fs");
fs.readFile('input.txt', function(err, data){
if(err) console.log(err.toString());
console.log(data.toString());
});
console.log('End of the program');
編譯器怎麼知道有錯誤會觸發err
,而data
會是從文件中讀取的數據嗎?
和參數的順序有關嗎?如果是,我怎麼知道我可以使用多少個參數?
編輯抱歉,沒有正確閱讀文檔。
參考解法
方法 1:
Yes, it's by the order of the arguments.
And you'd know by the documentation.
The callback is passed two arguments
(err, data)
, wheredata
is the contents of the file.
You might also take a look at Node style callbacks under the Node.js Errors docs.
方法 2:
How does the compiler know that err will be triggered if there is an error, and data will be the data read from the file?
Because the code for readFile
defines it as such.
Is it related to the order of the argument?
Yes. Just like any other function call.
If yes, how can I know how many arguments I can use?
By reading the documentation (or source code) for the function that calls your callback.