zoukankan      html  css  js  c++  java
  • Node.js-核心模块-zlib

    本文学习自:
    Node.js-核心模块-zlib
    https://blog.csdn.net/u012054869/article/details/83344848
    Zlip

    (1) gzip压缩
    Gzip.createGzip()
    (2) Zlib对象
    Gzip.createGunzip()

    
    // 导入模块
    const fs = require('fs');
    const zlib = require('zlib');
    // 创建文件的可读流
    const rs = fs.createReadStream('./data.txt');
     
    // 创建文件的可写流
    const ws = fs.createWriteStream('./data.txt.gzip');
    // 创建gzip压缩 流对象,gzip可读可写
    const gzip =zlib.createGzip();
    // 管道操作
    rs.pipe(gzip).pipe(ws);
    

    例子:使用命令压缩和解压缩文件
    命令行输入:node 2.js a.txt a.txt.gzip

    // 导入模块
    const fs = require('fs');
    const zlib = require('zlib');
    let src;
    let dst;
    // 获取压缩的源文件和目录文件
    if (process.argv[2]) {
        src = process.argv[2];
    } else {
        throw new Error('请指定源文件');
    }
    if (process.argv[3]) {
        dst = process.argv[3];
    } else {
        throw new Error('请指定目标文件');
    }
    // 创建文件的可读流
    const rs = fs.createReadStream(src);
    // 创建文件的可写流
    const ws = fs.createWriteStream(dst);
     
    const gzip =zlib.createGzip();
    // 管道操作
    rs.pipe(gzip).pipe(ws)
    

    解压缩:node 3.js a.txt.gzip b.txt

    
    / 导入模块
    const fs = require('fs');
    const zlib = require('zlib');
    // 判断存在参数
    if (!process.argv[2] && !process.argv[3]) {
        throw new Error('请指定参数');
    }
    // 创建文件的可读流
    const rs = fs.createReadStream(process.argv[2]);
    // 创建文件的可写流
    const ws = fs.createWriteStream(process.argv[3]);
    const gzip =zlib.createGunzip();
    // 管道操作
    rs.pipe(gzip).pipe(ws);
    console.log('解压成功')
    

    浏览器打开网页下载文件:

    //导入模块
    const http = require('http');
    const fs = require('fs');
    const zlib = require('zlib');
    //创建http服务
    http.createServer((req, res) => {
        const rs = fs.createReadStream('./index.html');
        //判断 浏览器是否需要 压缩版的
        if (req.headers['accept-encoding'].indexOf('gzip') != -1) {
            //设置响应头
            res.writeHead(200, {
               'content-encoding': 'gzip'
            });
            rs.pipe(zlib.createGzip()).pipe(res);
        } else {
            //不压缩
            rs.pipe(res);
        }
    }).listen(8080, () => {
        console.log('http server is running on port 8080');
    });
    
  • 相关阅读:
    Linux-通过破解Root密码来更改用户密码
    测验1:Python基本语法元素(第一周)
    Visual Studio 2019的安装&编写第一个C程序
    STL-vector之邻接表的建立
    分块-区间求和
    代码阅读方法与实践阅读笔记04
    代码阅读方法与实践阅读笔记03
    代码阅读方法与实践阅读笔记02
    代码阅读方法与实践阅读笔记01
    我们应当怎样做需求分析--阅读笔记
  • 原文地址:https://www.cnblogs.com/smart-girl/p/12596539.html
Copyright © 2011-2022 走看看