在web性能优化的时候,经常会使用到压缩神器gzip。当客户端(浏览器)向服务端发起资源请求时,服务器首先会对比较大的资源进行压缩,然后再返回给客户端,以此加快资源的访问速度。
下面来看压缩和解压缩的demo:
压缩:
// 使用gzip压缩
const fs = require('fs');
const zlib = require('zlib');
const gzip = zlib.createGzip();
const inFile = fs.createReadStream('./input.txt');
const outGzip = fs.createWriteStream('./input.txt.gz');
inFile.pipe(gzip)
.on('error', () => {
console.log('error');
})
.pipe(outGzip)
.on('error', () => {
console.log('error')
});
解压缩:
const fs = require('fs');
const zlib = require('zlib');
const gunzip = zlib.createGunzip();
const inGzipFile = fs.createReadStream('./input.txt.gz');
const outFile = fs.createWriteStream('./input1.txt');
inGzipFile.pipe(gunzip)
.on('error', () => {
console.log('错误处理');
})
.pipe(outFile)
.on('error', () => {
console.log('错误处理')
});
由上面的压缩和解压缩示例,用到了zlib这个模块,zlib模块提供了对Gzip/Gunzip, Deflate/Inflate, 和 DeflateRaw/InflateRaw类的绑定。每个类都有相同的参数和可读/写的流。在压缩资源时,使用zlib.createGzip(), 在解压缩文件时,使用zlib.createGunzip(),可以通过倒流(pipe)一个fs.ReadStream到zlib里面,再倒流一个fs.WriteStream。
上面对文件进行了压缩,也可以压缩数据,如下:
const fs = require('fs');
const zlib = require('zlib');
let data = 'This is a gzip application';
// 使用deflate压缩数据
zlib.deflate(data, (err, buffer) => {
if (!err) {
console.log(buffer.toString('base64')); // 以base64压缩
}
})
// 通过自动检测头解压缩一个Gzip-或Deflate-compressed流。
var buffer = new Buffer('eJwLycgsVgCiRIX0qswChcSCgpzM5MSSzPw8AHxuCaQ=', 'base64');
zlib.unzip(buffer, function(err, buffer) {
if (!err) {
console.log(buffer.toString());
};
本文介绍了在web性能优化中如何利用Node.js的zlib模块进行文件和数据的压缩与解压缩。通过创建Gzip和Gunzip对象,结合fs模块的ReadStream和WriteStream,可以方便地对资源进行压缩和解压缩操作。

828

被折叠的 条评论
为什么被折叠?



