亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從fs.readFile獲取數據

從fs.readFile獲取數據

拉風的咖菲貓 2019-07-22 15:06:11
從fs.readFile獲取數據var content;fs.readFile('./Index.html', function read(err, data) {     if (err) {         throw err;     }     content = data;});console.log(content);原木undefined為什么?
查看完整描述

3 回答

?
慕的地6264312

TA貢獻1817條經驗 獲得超6個贊

您定義的函數是一個異步回調。它不是立即執行,而是在文件加載完成后執行。調用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});


查看完整回答
反對 回復 2019-07-22
?
溫溫醬

TA貢獻1752條經驗 獲得超4個贊

function readContent(callback) {
    fs.readFile("./Index.html", function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })}readContent(function (err, content) {
    console.log(content)})


查看完整回答
反對 回復 2019-07-22
  • 3 回答
  • 0 關注
  • 1334 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號