您定義的函數是一個異步回調。它不是立即執行,而是在文件加載完成后執行。調用readFile時,將立即返回控件,并執行下一行代碼。因此,當您調用控制臺日志時,您的回調尚未被調用,并且尚未設置此內容。歡迎使用異步編程。
示例方法
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示例所示,將調用包裝在一個函數中,并傳遞您自己的回調。(顯然,這是更好的實踐),我認為,養成將異步調用包裝在函數中進行回調的習慣,將為您節省大量的麻煩和混亂的代碼。
function doSomething (callback) {
// any async callback invokes callback with response}doSomething (function doSomethingAfter(err, result) {
// process the async result});