【问题标题】:How to use zlib.gzipSync(buffer[, options]) for compressing files, and zlib.gunzipSync(buffer[, options]) for decompressing files?如何使用 zlib.gzipSync(buffer[, options]) 压缩文件,使用 zlib.gunzipSync(buffer[, options]) 解压缩文件?
【发布时间】:2020-10-04 10:22:01
【问题描述】:

大家好

我一直在思考如何在同步模式下使用 zlib,(同步模式对我来说很重要)

我尝试过多次失败,节点文档不完全清楚,缺少使用示例

我打算做的是:

一个函数 将包含一些数据的文本文件“myfile.txt”压缩为“Some text”并将其保存为“myfile.txt.gz”

function zip(fullPathToFile){
  const zlib= require('zlib');

  //some cool stuff...using:

  zlib.gzipSync(buffer[, options])

}

将“myfile.txt.gz”解压成“myfile.txt”的函数

function unZip(fullPathToFile){
  const zlib= require('zlib');

  //some cool stuff...using:

  zlib.gunzipSync(buffer[, options])

}

都在同一个目录中

有什么想法吗?

感谢大家的阅读和帮助

【问题讨论】:

    标签: javascript node.js gzip zlib unzip


    【解决方案1】:

    我首先使用fs.readFileSync 读取文件,然后将该缓冲区(数据)作为zlib.gzipSync 的第一个参数插入。出来的也是一个Buffer(压缩后的数据);我使用fs.writeFileSync 将其写入文件。

    const fs = require("fs");
    const zlib = require("zlib");
    function zip(path) {
        let data = fs.readFileSync(path);
        data = zlib.gzipSync(data);
        fs.writeFileSync(`${path}.gz`, data);
    }
    

    对于解压缩,将zlib.gzipSync 替换为zlib.gunzipSync 是您需要进行的唯一编辑。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多