[英]How to export chunk in http.request in node.js
此http.request代碼來自http://nodejs.org/docs/v0.4.7/api/http.html#http.request 。 如何在res.on中導出塊 ?
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
我不確定“導出”是什么意思,但也許您想將響應的內容放入本地文本文件中?
您可以按照以下步驟進行操作:
var http = require('http');
var fs = require('fs');
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
var response;
if(fs.existsSync('response.html'))
response = fs.readFileSync('response.html') + chunk;
else
response = chunk;
fs.writeFileSync('response.html', response);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
請注意,在觸發每個data
事件之后,我們將使用fs.existsSync
檢查現有文件,並fs.existsSync
填充響應變量,然后使用fs.writeFileSync
將響應再次寫入文件。
這在服務器上用處不大,因為文件讀/寫的同步特性將成為您流量的瓶頸,但是它的確突出了響應事件和連接塊的一般概念。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.