概览
做过web性能优化的同学,对性能优化大杀器gzip应该不陌生。浏览器向服务器发起资源请求,比如下载一个js文件,服务器先对资源进行压缩,再返回给浏览器,以此节省流量,加快访问速度。
浏览器通过http请求头部里加上accept-encoding,告诉服务器,“你可以用gzip,或者defalte算法压缩资源”。
accept-encoding:gzip, deflate
那么,在nodejs里,是如何对资源进行压缩的呢?答案就是zlib模块。
入门实例:简单的压缩/解压缩
压缩的例子
非常简单的几行代码,就完成了本地文件的gzip压缩。
var fs = require('fs');
var zlib = require('zlib');
var gzip = zlib.creategzip();
var infile = fs.createreadstream('./extra/fileforcompress.txt');
var out = fs.createwritestream('./extra/fileforcompress.txt.gz');
infile.pipe(gzip).pipe(out);
解压的例子
同样非常简单,就是个反向操作。
var gunzip = zlib.creategunzip();
var infile = fs.createreadstream('./extra/fileforcompress.txt.gz');
var outfile = fs.createwritestream('./extra/fileforcompress1.txt');
infile.pipe(gunzip).pipe(outfile);
服务端gzip压缩
代码超级简单。首先判断 是否包含 accept-encoding 首部,且值为gzip。
否:返回未压缩的文件。
是:返回gzip压缩后的文件。
var http = require('http');
var filepath = './extra/fileforgzip.html';
var server = http.createserver(function(req, res){
var acceptencoding = req.headers['accept-encoding'];
var gzip;
if(acceptencoding.indexof('gzip')!=-1){ // 判断是否需要gzip压缩
gzip = zlib.creategzip();
// 记得响应 content-encoding,告诉浏览器:文件被 gzip 压缩过
res.writehead(200, {
'content-encoding': 'gzip'
});
fs.createreadstream(filepath).pipe(gzip).pipe(res);
}else{
fs.createreadstream(filepath).pipe(res);
}
});
server.listen('3000');
服务端字符串gzip压缩
代码跟前面例子大同小异。这里采用了slib.gzipsync(str)对字符串进行gzip压缩。
var responsetext = 'hello world';
if(acceptencoding.indexof('gzip')!=-1){
res.end( zlib.gzipsync(responsetext) );
res.end(responsetext);
写在后面
作者:程序猿小卡_casper
来源:51cto