【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端口已启动...')
})
相关推荐
小p21 小时前
nodejs学习6:nodejs应用的优雅退出
node.js
军哥全栈AI1 天前
Windows11 彻底卸载Node.js(无残留,适配所有版本)
npm·node.js
困惑阿三1 天前
全栈部署排雷手册:从 405 报错到飞书推送成功
服务器·前端·后端·nginx·阿里云·node.js·飞书
Andytoms1 天前
Node.js 版本和 pnpm 版本的对应关系
node.js
头发多多程序媛2 天前
解决依赖下载报错,npm ERR! code EPERM
前端·npm·node.js
fanjinzhi2 天前
Node.js通用计算15--TypeScript介绍
javascript·typescript·node.js
light blue bird2 天前
MES/ERP的Web多页签报表系统
数据库·node.js·ai大数据·mes/erp·web报表
Doris8932 天前
【Node.js 】Node.js 与 Webpack 模块化工程化入门指南
前端·webpack·node.js
alanesnape2 天前
在 Surface Pro X (ARM64) 上成功部署 Claude Code 的完整复盘
git·node.js·claude code部署·msys2clangarm64·美区apple id·礼品卡支付·surface pro x