【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端口已启动...')
})
相关推荐
网络点点滴7 小时前
NPM的包版本管理
前端·npm·node.js
Allen正心正念20258 小时前
前端——Node.js&npm,学点前端的东西
前端·npm·node.js
. . . . .9 小时前
Node.js 模块系统
node.js
我叫汪枫19 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
技术钱19 小时前
nodejs使用RustFS容器服务搭建对象存储oss
node.js·egg
大貔貅喝啤酒1 天前
接口测试_Postman(详细版)
javascript·测试工具·node.js·自动化·postman
桜吹雪1 天前
Langchain.js官方文档:构建具备按需加载技能的 SQL 助手
javascript·人工智能·node.js
拾贰_C1 天前
【node.js | Ubuntu | update】如何升级旧的nodejs本版至最新;如何升级npm
ubuntu·npm·node.js
湖边看客1 天前
在 Windows PowerShell 里给 Node.js 设置内存上限
node.js
zhensherlock1 天前
Protocol Launcher 系列:Beorg 高效任务管理的协议支持
前端·javascript·typescript·node.js·自动化·github·js