【问题标题】:How to gunzip stream in nodejs?如何在nodejs中压缩流?
【发布时间】:2016-06-30 10:17:30
【问题描述】:

我正在尝试完成一项相当简单的任务,但我有点困惑并坚持在 nodejs 中使用 zlib。我正在构建功能,包括从 gzip 压缩的 aws S3 下载文件、解压缩并逐行读取。我想使用流来完成所有这些,因为我相信在 nodejs 中可以这样做。

这是我当前的代码库:

//downloading zipped file from aws s3:
//params are configured correctly to access my aws s3 bucket and file

s3.getObject(params, function(err, data) {
  if (err) {
    console.log(err);
  } else {

    //trying to unzip received stream:
    //data.Body is a buffer from s3
    zlib.gunzip(data.Body, function(err, unzippedStream) {
      if (err) {
        console.log(err);
      } else {

        //reading line by line unzziped stream:
        var lineReader = readline.createInterface({
          input: unzippedStream
        });
        lineReader.on('line', function(lines) {
          console.log(lines);
        });
      }
    });
  }
});

我收到一条错误消息:

 readline.js:113

        input.on('data', ondata);
              ^

    TypeError: input.on is not a function

我认为解压缩过程中可能存在问题,但我不太确定出了什么问题,我们将不胜感激。

【问题讨论】:

    标签: node.js stream zlib gunzip


    【解决方案1】:

    我没有要测试的 S3 帐户,但 reading the docs 建议 s3.getObject() 可以返回一个流,在这种情况下,我认为这可能有效:

    var lineReader = readline.createInterface({
      input: s3.getObject(params).pipe(zlib.createGunzip())
    });
    lineReader.on('line', function(lines) {
      console.log(lines);
    });
    

    编辑:看起来 API 可能已更改,您现在需要 instantiate a stream object manually 才能通过其他任何内容进行管道传输:

    s3.getObject(params).createReadStream().pipe(...)
    

    【讨论】:

    • 这确实有效..全部在一行而不是我拥有的 3 个函数..我所要做的就是添加 .createReadStream() 就像在s3.getObject(params).createReadStream().pipe(zlib.createGunzip()) 中一样,它工作得很好。现在我只需要包含一些错误处理,谢谢先生!
    • 这不起作用:TypeError: s3.getObject(...).pipe is not a function
    • @loretoparisi 我猜API已经改变了,试试s3.getObject(...).createReadStream().pipe()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-30
    • 2016-11-29
    • 2020-06-22
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 2014-03-31
    相关资源
    最近更新 更多