js实现gzip
Gzip 压缩的实现方法
在 JavaScript 中实现 Gzip 压缩可以通过浏览器端的 API 或 Node.js 环境下的模块来完成。以下是两种常见场景的具体实现方法。
浏览器端使用 pako 库
pako 是一个流行的 JavaScript 库,支持 Gzip 压缩和解压,适用于浏览器环境。
安装 pako:
npm install pako
压缩字符串示例:

import pako from 'pako';
const originalString = 'This is a string to be compressed with Gzip.';
const compressed = pako.gzip(originalString);
const compressedString = String.fromCharCode.apply(null, compressed);
console.log('Compressed:', compressedString);
解压示例:
const decompressed = pako.ungzip(compressed);
const decompressedString = String.fromCharCode.apply(null, decompressed);
console.log('Decompressed:', decompressedString);
Node.js 使用 zlib 模块
Node.js 内置了 zlib 模块,可以直接用于 Gzip 压缩和解压。
压缩文件示例:

const fs = require('fs');
const zlib = require('zlib');
const gzip = zlib.createGzip();
const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');
input.pipe(gzip).pipe(output);
解压文件示例:
const gunzip = zlib.createGunzip();
const input = fs.createReadStream('input.txt.gz');
const output = fs.createWriteStream('input-decompressed.txt');
input.pipe(gunzip).pipe(output);
压缩 HTTP 响应
在 Node.js 的 HTTP 服务器中,可以使用 zlib 动态压缩响应数据。
示例代码:
const http = require('http');
const zlib = require('zlib');
http.createServer((req, res) => {
const responseText = 'Hello, this is compressed content.';
zlib.gzip(responseText, (err, buffer) => {
if (err) {
res.writeHead(500);
res.end();
return;
}
res.writeHead(200, {
'Content-Encoding': 'gzip',
'Content-Type': 'text/plain'
});
res.end(buffer);
});
}).listen(3000);
注意事项
- 浏览器端的 Gzip 压缩通常用于特定场景,如大型文本或二进制数据的传输优化。
- Node.js 的
zlib模块性能较高,适合服务器端的数据压缩需求。 - 压缩后的数据通常需要转换为 Base64 或二进制字符串进行传输或存储。
- 解压时需要确保数据格式与压缩时一致,避免数据损坏。






