标签:
现如今在处理http请求的时候,由于请求的资源较多,如果不启用压缩的话,那么页面请求的流量将会非常大。启用gzip压缩,在一定程度上会大大的提高页面性能。
var fs = require(‘fs‘); var zlib = require(‘zlib‘); var http = require(‘http‘); http.createServer(function (req, res){ var raw = fs.createReadStream(‘test.txt‘); var acceptEncoding = req.headers[‘accept-encoding‘]; if (!acceptEncoding){ acceptEncoding = ‘‘; } if (acceptEncoding.match(/\bdeflate\b/)){ res.write(200, {‘content-encoding‘: ‘deflate‘}); raw.pipe(zlib.createDeflate()).pipe(res); } else if (acceptEncoding.match(/\bgzip\b/)){ res.write(200, {‘content-encoding‘: ‘gzip‘}); raw.pipe(zlib.createGzip()).pipe(res); } else{ res.write(200, {}); raw.pipe(res); } }).listen(1337, ‘127.0.0.1‘);
var fs = require(‘fs‘); var zlib = require(‘zlib‘); var http = require(‘http‘); var options = { host: ‘localhost‘, path: ‘/‘, port: 1337, headers: {‘accept-encoding‘: ‘gzip, deflate‘} }; var request = http.get(options) ; request.on(‘response‘, function (res){ var output = fs.createWriteStream(‘test2.txt‘); var codeStr = res.headers[‘content-encoding‘]; switch (codeStr){ case ‘gzip‘: res.pipe(zlib.createGunzip()).pipe(output); break; case ‘deflate‘: res.pipe(zlib.createInflate()).pipe(output); break; default : res.pipe(output); break } });
标签:
原文地址:http://www.cnblogs.com/duhuo/p/4773059.html