您定義的函數(shù)是一個異步回調(diào)。它不是立即執(zhí)行,而是在文件加載完成后執(zhí)行。調(diào)用readFile時,將立即返回控件,并執(zhí)行下一行代碼。因此,當(dāng)您調(diào)用控制臺日志時,您的回調(diào)尚未被調(diào)用,并且尚未設(shè)置此內(nèi)容。歡迎使用異步編程。
示例方法
const fs = require('fs');var content;// First I want to read the filefs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it});function processFile() {
console.log(content);}
或者更好的是,如Raynos示例所示,將調(diào)用包裝在一個函數(shù)中,并傳遞您自己的回調(diào)。(顯然,這是更好的實踐),我認(rèn)為,養(yǎng)成將異步調(diào)用包裝在函數(shù)中進(jìn)行回調(diào)的習(xí)慣,將為您節(jié)省大量的麻煩和混亂的代碼。
function doSomething (callback) {
// any async callback invokes callback with response}doSomething (function doSomethingAfter(err, result) {
// process the async result});