【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端口已启动...')
})
相关推荐
见过夏天2 天前
Node.js 常用命令全攻略
node.js
前端双越老师2 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen3 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding3 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt4 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好5 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊7 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
糖拌西瓜皮7 天前
Node.js核心模块实战:文件、路径、HTTP与流处理
javascript·node.js
糖拌西瓜皮7 天前
Node.js工程化实践:包管理、TypeScript配置与代码质量
typescript·node.js
糖拌西瓜皮7 天前
NestJS入门指南:Java开发者的Spring Boot体验
javascript·node.js