登录
注册
node.js 学习社区
node.js 管道压缩 与 非管道压缩

幸福港湾

2015-03-10 22:17

管道压缩

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']) {
        case 'gzip':
            response.pipe(zlib.createGunzip()).pipe(output);
            break;
        case 'deflate':
            response.pipe(zlib.createInflate()).pipe(output);
            break;
        default:
            response.pipe(output);
            break;
    }
});
非管道压缩

var http = require('http');
var querystring = require('querystring');
var 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',
        'Content-Length': args.contents.length,
        'User-Agent':'Mozilla/5.0 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'];
        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);
});

回复 · 0

发表回复

你可以在回复中 @ 其他人