寫http時候,在接收http請求時候,出現亂碼,後來發現是gzip沒有解壓。node
關於gzip/deflate壓縮,有放入管道壓縮,和非管道壓縮方法。web
代碼以下:網絡
#! /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); });
Node中的I/O是異步的,所以對磁盤和網絡的讀寫須要經過回調函數來讀取數據。app
當內存中沒法一次裝下須要處理的數據時,或者一邊讀取一邊處理更加高效時,咱們就須要用到數據流。異步
NodeJS中經過各類Stream來提供對數據流的操做。函數
官網提供了管道方法:ui
// 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; } });
2015-03-03 14:17:20code