【Node.js】zlib

gzip 和 deflate 的基本使用

js 复制代码
const zlib = require("zlib");
const fs = require('fs')

// 压缩 1. createGzip .gz  2. createDeflate .deflate
// const readStream = fs.createReadStream('index.txt')
// const writeStream = fs.createWriteStream('index.txt.gz')
// readStream.pipe(zlib.createGzip()).pipe(writeStream)

//解压 1. createGunzip  2. createInflate
// const readStream = fs.createReadStream('index.txt.gz')
// const writeStream = fs.createWriteStream('index2.txt')
// readStream.pipe(zlib.createGunzip()).pipe(writeStream)

const readStream = fs.createReadStream('index.txt')
const writeStream = fs.createWriteStream('index.txt.deflate')
readStream.pipe(zlib.createDeflate()).pipe(writeStream)

gzip 和 deflate 的区别

  1. 压缩算法:Gzip 使用 LZ77 算法和哈夫曼编码。所以 gzip 慢于 deflate 且压缩后文件大于 deflate。

  2. 应用场景:Gzip 压缩常用于文件压缩,deflate 适用于网络传输和 HTTP 响应的内容编码。

js 复制代码
const zlib = require("zlib");
const http = require('http')
// 直接写入 17.2 kB / gzip 289 B / deflate 279 B
const server = http.createServer((req,res)=> {
    const txt = '我是糕手 O.o '.repeat(1000)
    res.setHeader('Content-Encoding', 'deflate')
    res.setHeader('Content-Type', 'text/plan;charset=utf-8')
    let result = zlib.deflateSync(txt)
    res.end(result)
})
server.listen(3000,()=> {
    console.log('服务器3000端口已启动...')
})
相关推荐
哪里不会点哪里.9 小时前
NVM:Node.js 版本管理工具
node.js
小小的梦想!12 小时前
mac切换node版本
macos·node.js
夏沫mds12 小时前
Node.js 实现高保真 PDF 压缩:从 Canvas 方案到 Ghostscript 的踩坑实录
pdf·node.js
lichenyang4531 天前
从语雀到本地:打造一个文档导出工具
node.js
新缸中之脑1 天前
NodeLLM:Node.js的AI基础设施
人工智能·node.js
csdn_aspnet1 天前
JavaScript常用算法深度解析:从浏览器到Node.js的实战
javascript·node.js
michael_ouyang1 天前
IM 会话同步企业级方案选型
前端·websocket·electron·node.js
绝世这天下1 天前
【使用 NVM 安装 Node.js 22 并配置国内镜像加速】
node.js
EndingCoder2 天前
Node.js 与 TypeScript:服务器端开发
前端·javascript·typescript·node.js
web小白成长日记2 天前
Node.js 编程实战:部署 Node.js 应用 —— Docker 容器化部署
docker·容器·node.js