撰寫 HTTP 相關程式時,若收到伺服器回傳的 gzip 壓縮內容卻沒有解壓,畫面上就會出現一堆亂碼。本文整理 Node.js 中處理 gzip/deflate 的兩種典型路徑:串流管道式與一次性緩衝式。
Node 的 I/O 是異步的,因此對磁碟與網路的讀寫都需要透過回呼函式來取得資料。當記憶體無法一次裝下要處理的資料,或者「一邊讀、一邊處理」更有效率時,就該使用資料流(Stream)。Node 透過各種 Stream 物件提供對資料流的操作,而 pipe 就是串接它們的方法。
官方文件提供的範例寫法如下:
// client request example
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
var request = http.get({ host: 'homeway.me',
path: '/',
port: 80,
headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', function(response) {
var output = fs.createWriteStream('izs.me_index.html');
switch (response.headers['content-encoding']) {
// or, just use zlib.createUnzip() to handle both cases
case 'gzip':
response.pipe(zlib.createGunzip()).pipe(output);
break;
case 'deflate':
response.pipe(zlib.createInflate()).pipe(output);
break;
default:
response.pipe(output);
break;
}
});
重點是依據回應標頭裡的 content-encoding 選擇對應的解壓串流:gzip 用 createGunzip(),deflate 用 createInflate(),兩者都沒有就原樣輸出。註解中也提到,若不想分支處理,可以直接用 zlib.createUnzip() 一次搞定兩種編碼。串流式的優點是記憶體占用穩定,不論檔案多大都不必全部載入。
若你更習慣「收完再處理」的寫法,可以先收集所有 chunk,合併成 Buffer 後再一次解壓:
#! /usr/local/bin/node
var http = require('http'),
querystring = require('querystring'),
zlib = require('zlib');
var args = {
//參數以及備用數據
contents : querystring.stringify({
//發包的信息
name:'homeway.me',
}),
};
var options = {
hostname: 'homeway.me',
port: 80,
path: '/',
method: 'GET',
headers: {
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Content-Length': args.contents.length,
'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.11 Safari/537.36',
'Accept-Encoding':'gzip, deflate',
},
};
var get = function ( options, args, callback ){
var req = http.request(options, function (res) {
var chunks =[], data, encoding = res.headers['content-encoding'];
// 非gzip/deflate要轉成utf-8格式
if( encoding === 'undefined'){
res.setEncoding('utf-8');
}
res.on('data', function (chunk){
chunks.push(chunk);
});
res.on('end', function (){
var buffer = Buffer.concat(chunks);
if (encoding == 'gzip') {
zlib.gunzip(buffer, function (err, decoded) {
data = decoded.toString();
callback( err, args, res.headers, data);
});
} else if (encoding == 'deflate') {
zlib.inflate(buffer, function (err, decoded) {
data = decoded.toString();
callback( err, args, res.headers, data);
});
} else {
data = buffer.toString();
callback( null, args, res.headers, data);
}
});
});
req.write( args.contents );
req.end();
};
get( options, args, function (err, args, headers, data){
console.log('==>header \n', headers);
console.log('==data \n', data);
});
這裡有兩個細節值得注意。第一,在 data 事件中只把 chunk 推進陣列而不做任何處理,等到 end 事件才用 Buffer.concat 合併——這是因為壓縮資料必須完整才能解開,中途分段解壓是行不通的。第二,程式用 res.setEncoding('utf-8') 處理未壓縮的情況,但嚴格來說應該判斷 res.headers['content-encoding'] 是否存在,而不是拿字串 'undefined' 來比對,這裡是原範例可以再加強的地方。
串流式的優勢在於記憶體可預測,適合處理大型回應或需要邊收邊寫檔的情境;緩衝式則勝在邏輯直白、方便對整份內容做一次性處理,適合中小型回應。理解兩者之後,就能依場景做出合適的取捨。
以上就是 Node.js 關於 gzip/deflate 壓縮處理的整理,希望大家能夠喜歡。