Node.js: Download file from s3 and unzip it to a string

吃可爱长大的小学妹 提交于 2019-12-10 20:14:12

问题


I am writing an AWS Lambda function which needs to download files from AWS S3, unzips the file and returns the content in the form of a string.

I am trying this

function getObject(key){
  var params = {
    Bucket: "my-bucket",
    Key: key
  }
  return new Promise(function (resolve, reject){
    s3.getObject(params, function (err, data){
      if(err){
        reject(err);
      }
      resolve(zlib.unzipSync(data.Body))
    })
  })
}

But getting the error

Error: incorrect header check
    at Zlib._handle.onerror (zlib.js:363:17)
    at Unzip.Zlib._processChunk (zlib.js:524:30)
    at zlibBufferSync (zlib.js:239:17)

The data looks like this

{ AcceptRanges: 'bytes',
  LastModified: 'Wed, 16 Mar 2016 04:47:10 GMT',
  ContentLength: '318',
  ETag: '"c3xxxxxxxxxxxxxxxxxxxxxxxxx"',
  ContentType: 'binary/octet-stream',
  Metadata: {},
  Body: <Buffer 50 4b 03 04 14 00 00 08 08 00 f0 ad 6f 48 95 05 00 50 84 00 00 00 b4 00 00 00 2c 00 00 00 30 30 33 32 35 2d 39 31 38 30 34 2d 37 34 33 30 39 2d 41 41 ... > 
}

回答1:


The Body buffer contains zip-compressed data (this is identified by the first few bytes), which is not just plain zlib.

You will need to use some zip module to parse the data and extract the files within. One such library is yauzl which has a fromBuffer() method that you can pass your buffer to and get the file entries.



来源:https://stackoverflow.com/questions/36082921/node-js-download-file-from-s3-and-unzip-it-to-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!