2012-08-05 78 views
2

使用Facebook圖形API時,我已經使用https.get來請求Facebook用戶數據。https.get響應ondata回調觸發多次

var optionsP = { 
     host: 'graph.facebook.com',  
     path: '/me?access_token=XXXX' 
    }; 

    https.get(optionsP, function(resp) {           
     resp.on('data', function(d) {         
      console.log('ondata') 
      console.log(d.length) 
      process.stdout.write(d) 
     }); 
    }).on('error', function(e) { 
     console.error(e); 
}); 

但是響應數據來自2部分!第一次打印多達1034個字符,然後再次同樣的回調將工作並打印剩餘的1347個字符。這些部分迴應的原因是什麼?

回答

8

這很正常。 resp是一個流。它是一個ClientResponse對象,它實現了可讀的流接口。以下是文檔:http://nodejs.org/api/http.html#http_http_clientresponse

您可以將輸出管道輸出到接受流的地方,或者將其存儲在緩衝區中,直到您收到「結束」事件。

這裏是存儲在內存中的字符串中的數據爲例,直到它已全部抵達:

https.get(optionsP, function(resp) {           
    resp.setEncoding(); //Now the data is a string! 
    var store = ""; 
    resp.on('data', function(d) { 
     store += d; 
    }); 
    resp.on('end', function() { 
     console.log("this is all: " + store); 
    }); 
}).on('error', function(e) { 
    console.error(e); 
}); 
+0

感謝rdrey ......按照文檔「事件:數據發射時一塊的郵件正文被收到。「所以我們必須添加這些部分來創建一個完整的消息體。 :) – Vivek 2012-08-05 12:29:17

+0

沒錯。 :) – rdrey 2012-08-05 12:34:12