合适的GZIP流

发布于 2025-01-21 06:02:14 字数 765 浏览 1 评论 0原文

我正在尝试创建一个可以在其他地方重复使用的GZIP流。 GZIP可以很好地压缩数据流,但我想重构我的代码,以便可以分开关注。这样一来,我最终得到了以下内容。但是,我无法利用返回的流。

const zlib = require('zlib');

function compress(stream) {
  return new Promise((resolve, reject) => {
    const gzipStream = zlib.createGzip();

    gzipStream.on('end', () => {
      resolve(gzipStream);
    });

    gzipStream.on('error', (e) => {
      reject(e);
    });

    stream.pipe(gzipStream);
  });
}

但是,当我使用返回的流时,我将获得空输出。例如,我压缩一个充满0的50MB文件,使用新功能后,我将获得一个空文件。

async function handler(req, res) {
  const fileStream = fs.createReadStream("./test_50m");
  const compressedStream = await compress(fileStream);
  
  compressedStream.pipe(fs.createWriteStream("./test_50m_output"));
}

谢谢

I am trying to create a gzip stream which I can re-use elsewhere. Gzip works good to compress a stream of data but I wanted to refactor my code so I could seperate concerns. In doing so I ended up with the following. However, I can't utilised the returned stream.

const zlib = require('zlib');

function compress(stream) {
  return new Promise((resolve, reject) => {
    const gzipStream = zlib.createGzip();

    gzipStream.on('end', () => {
      resolve(gzipStream);
    });

    gzipStream.on('error', (e) => {
      reject(e);
    });

    stream.pipe(gzipStream);
  });
}

However I get empty output when I use the returned stream. E.g. I compress a 50mb file filled with 0's, and after using my new function, I get an empty file.

async function handler(req, res) {
  const fileStream = fs.createReadStream("./test_50m");
  const compressedStream = await compress(fileStream);
  
  compressedStream.pipe(fs.createWriteStream("./test_50m_output"));
}

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文