• 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');
    });
    
  • 相关阅读:
    软件开发沉思录读书笔记
    卓有成效的程序员读书笔记
    结对编程收获
    《提高c++性能的编程技术》读书笔记
    第六次读书笔记
    第五周读书笔记
    美团与它的超级大脑
    第四次读书笔记
    团队-团队编程项目爬取豆瓣电影top250-模块测试过程
    团队-爬取豆瓣电影TOP250-模块开发过程
  • 原文地址:https://www.cnblogs.com/smart-girl/p/12596539.html
Copyright © 2020-2023  润新知