[英]Convert node.js HTTP response function (using “request” library) to use streams
我在node.js中使用請求庫 ,該庫下載HTML正文響應,但以塊的形式進行。 目前,我只是將它們串聯到一個dataChunks
變量中,並使用一個被黑客入侵的測試來查看它們何時全部下載。 但是,我已經閱讀了Stream Handbook ,這似乎是使用流獲取數據塊的情況。 雖然我不完全了解該怎么做,所以不勝感激。 相關代碼如下:
var dataChunks = "";
request.get({ url: baseUrl + path })
.on("error", function(err) { throw new Error(err); })
.on("response", function(res) {
if (res.statusCode === 200) {
res.on("data", function(data) {
var dataString, dt;
dataChunks += (dataString = data.toString());
if ((dt = dataString.slice(-100).trimRight()).lastIndexOf("</html>") === dt.length - 7) {
// do stuff with dataChunks
}
});
}
});
預先感謝您的任何幫助。
您不需要為此的流。 從請求自述文件:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
})
流示例:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.