【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端口已启动...')
})
相关推荐
全栈前端老曹1 天前
【MongoDB】Node.js 集成 —— Mongoose ORM、Schema 设计、Model 操作
前端·javascript·数据库·mongodb·node.js·nosql·全栈
行者无疆_ty1 天前
什么是Node.js,跟OpenCode/OpenClaw有什么关系?
人工智能·node.js·openclaw
-凌凌漆-1 天前
【npm】npm的-D选项介绍
前端·npm·node.js
lucky67071 天前
Windows 上彻底卸载 Node.js
windows·node.js
Android系统攻城狮1 天前
鸿蒙系统Openharmony5.1.0系统之解决编译时:Node.js版本不匹配问题(二)
node.js·鸿蒙系统·openharmony·编译问题·5.1
清山博客1 天前
OpenCV 人脸识别和比对工具
前端·webpack·node.js
何中应1 天前
nvm安装使用
前端·node.js·开发工具
何中应1 天前
MindMap部署
前端·node.js
37方寸1 天前
前端基础知识(Node.js)
前端·node.js
朝朝暮暮an2 天前
Day 3|Node.js 异步模型 & Promise / async-await(Part 1)
node.js