2014-05-20 38 views
2

我有一個客戶端的NodeJS是類似於HTTP的NodeJS後 - 的GZip

var options = { 
    hostname: '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); 
    }); 
}); 

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
}); 

// write data to request body 
req.write('data\n'); 
req.write('data\n'); 
req.end(); 

有什麼辦法,使在gzip壓縮在所有req.write數據元素?

回答

5

發送壓縮請求,數據壓縮成zlib緩衝區,然後把它寫爲你的輸出:

var zlib = require('zlib'); 
var options = { 
    hostname: 'www.example.com', 
    port: 80, 
    path: '/upload', 
    method: 'POST', 
    headers: {'Content-Encoding': 'gzip'} // signal server that the data is compressed 
}; 
zlib.gzip('my data\ndata\n', function (err, buffer) { 
    var req = http.request(options, function(res) { 
     res.setEncoding('utf8');// note: not requesting or handling compressed response 
     res.on('data', function (chunk) { 
      // ... do stuff with returned data 
     }); 
    }); 
    req.on('error', function(e) { 
     console.log('problem with request: ' + e.message); 
    }); 

    req.write(buffer); // send compressed data 
    req.end(); 
}); 

這應該發送一個gzipped請求到服務器並得到一個非壓縮的響應。查看處理壓縮響應的這個問題的其他答案。

-1
var zlib = require('zlib'); 
var gunzip = zlib.createGunzip(); 

var options = { 
    hostname: 'www.google.com', 
    port: 80, 
    path: '/upload', 
    method: 'POST', 
    headers: {'Accept-Encoding': 'gzip'} 
}; 

var req = http.request(options); 

gunzip.on('data', function (buf) { 
    body += buf.toString(); 
}); 

gunzip.on('end', function() { 
    console.log(body); 
    // do whatever you want to do with body 
}); 

req.on('error', function(e) { 
    console.log('problem with request: ' + e.message); 
    gunzip.end(); 
}); 

req.pipe(gunzip); 
上zlib庫

更多信息:http://nodejs.org/api/zlib.html

+2

我認爲他們想要另一種方式...發送一個gzipped請求正文。這將需要設置標題:{'Content-Encoding':'gzip'}'並使用Gzip流和管道req來代替。 – mscdex