01 zlib模块

简述

zlib 模块是用来压缩文件的,在http协议的请求头中设置Accept-Encoding: gzip, 表示告诉服务器我请求的资源可以使用gzip进行压缩,优化了下载的速度

简单压缩

    const fs = require('fs')
    const zlib = require('zlib')
    const gzip = zlib.createGzip()
    fs.createReadStream('./hello.txt').pipe(gzip).pipe(fs.createWriteStream('./hello.txt.gz'))

简单解压

    const fs = require('fs')
    const zlib = require('zlib')
    const gunzip = zlib.createGunzip()
    fs.createReadStream('./hello.txt.gz').pipe(gunzip).pipe(fs.createWriteStream('./hello.txt'))

服务端压缩

    const fs = require('fs')
    const http = require('http')
    const zlib = require('zlib')
    const gzip = zlib.createGzip()
    const server = http.createServer((req, res) => {
        const acceptEncoding= req.headers['accept-encoding']
        if(acceptEncoding.indexOf('gzip') !== -1) {
            res.writeHead(200,{
                'content-encoding': 'gzip'
            })
            fs.createReadStream('./index.html').pipe(gzip).pipe(res)
        }else {
            fs.createReadStream('./index.html').pipe(res)
        }
    })
    server.listen('3000')

服务端压缩字符串

    const fs = require('fs')
    const http = require('http')
    const zlib = require('zlib')
    
    const server = http.createServer((req, res) => {
        const acceptEncoding = req.headers['accept-encoding']
        if(acceptEncoding.indexOf('gzip') !== -1) {
            res.writeHead(200, {
                'content-encoding': 'gzip'
            })
            res.end(zlin.gzipSync('hello node'))
        }else {
            res.end('hello node')
        }
    })
    
    server.listen('3000')

学模块步骤

  1. 看github上的这个项目
  2. 自己写一遍,传到自己的github项目
  3. 看node文档
  4. 复习一篇博客
posted @ 2020-02-18 10:22  达文西9527  阅读(152)  评论(0编辑  收藏  举报