【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端口已启动...')
})
相关推荐
coderCN1 天前
Nodejs 响应头和请求头
后端·node.js
__zRainy__1 天前
Node系列 · ORM:log4js 日志记录
node.js·log4j
秋秋小事1 天前
node 导入与导出
node.js
秋秋小事2 天前
node event模块
node.js
晴天162 天前
Node.js 中 `npm install` 命令分析-Day30
前端·npm·node.js
晴天162 天前
VS Code `launch.json` 指南(Node.js版)-Day30
node.js·json
空の鱼2 天前
Mac 上 Node 版本管理(brew + nvm 共存方案)
macos·node.js
请你吃div2 天前
Node 后端项目 Docker 自动部署教程(GitHub + 宝塔 + Self-hosted Runner)
后端·docker·node.js
泠曦れいひ2 天前
在当前项目中安装Vite
前端框架·npm·node.js
Joseph 乔2 天前
【NVM】node 和 nvm 卸载(安装 node & nvm & npm & cnpm & yarn 及配置)
npm·node.js