• web页面如下
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <ul>
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
            ... 省略
            <li>9991</li>
            <li>10001</li>
        </ul>
    </body>
    </html>
    
  • 服务器代码如下
    const express = require("express");
    const app = express();
    const path = require("path");
    const fs = require("fs");
    const zlib = require("zlib");
    
    
    app.get("/", (req, res) => {
        const filePath = path.resolve(__dirname, "./index.html");
        const rs = fs.createReadStream(filePath);
    
        //获取请求中的Accept-Encoding可以接受的类型,根据可以接受的类型来完成压缩选择
        console.log(req.headers["accept-encoding"]);
        const acceptEncoding = req.headers["accept-encoding"];
        //可以使用includes判断字符串中是否含有某个值
        if (acceptEncoding.includes("gzip")) {
            const zlibFile = rs.pipe(zlib.createGzip())
            res.set("Content-Encoding", "gzip")
            return zlibFile.pipe(res);
        }
    
        if (acceptEncoding.includes("deflate")) {
            const zlibFile = rs.pipe(zlib.createDeflate())
            res.set("Content-Encoding", "deflate")
            return zlibFile.pipe(res);
        }
    
        if (acceptEncoding.includes("br")) {
            const zlibFile = rs.pipe(zlib.createBrotliCompress())
            res.set("Content-Encoding", "br")
            return zlibFile.pipe(res);
        }
    
        //如果上边的条件都不符合,则不压缩 直接响应
        rs.pipe(res);
    
        //使用gZip压缩:创建一个新的gzip对象,并把文件写入这个对象中
        /* const zlibFile = rs.pipe(zlib.createGzip())
        res.set("Content-Encoding", "gzip") */
    
        /* const zlibFile = rs.pipe(zlib.createBrotliCompress())
        res.set("Content-Encoding", "br") */
    
        /* const zlibFile = rs.pipe(zlib.createDeflate())
        res.set("Content-Encoding", "deflate") */
    
        // zlibFile.pipe(res);
    })
    
    app.listen("3000", (err) => {
        if (err) {
            console.log(err);
            return;
        }
        console.log("http://127.0.0.1:3000");
    })
    
posted on 2021-06-10 16:27  文种玉  阅读(123)  评论(0编辑  收藏  举报