s3.getObject().createReadStream() : How to catch the error?

前端 未结 3 636
忘了有多久
忘了有多久 2021-01-03 18:29

I am trying to write a program to get a zip file from s3, unzip it, then upload it to S3. But I found two exceptions that I can not catch.

1.

3条回答
  •  伪装坚强ぢ
    2021-01-03 18:47

    You can listen to events (like error, data, finish) in the stream you are receiving back. Read more on events

    function getObjectStream (filePath) {
      return s3.getObject({
        Bucket: bucket,
        Key: filePath
      }).createReadStream()
    }
    
    let readStream = getObjectStream('/path/to/file.zip')
    readStream.on('error', function (error) {
      // Handle your error here.
    })
    

    Tested for "No Key" error.

    it('should not be able to get stream of unavailable object', function (done) {
      let filePath = 'file_not_available.zip'
    
      let readStream = s3.getObjectStream(filePath)
      readStream.on('error', function (error) {
        expect(error instanceof Error).to.equal(true)
        expect(error.message).to.equal('The specified key does not exist.')
        done()
      })
    })
    

    Tested for success.

    it('should be able to get stream of available object', function (done) {
      let filePath = 'test.zip'
      let receivedBytes = 0
    
      let readStream = s3.getObjectStream(filePath)
      readStream.on('error', function (error) {
        expect(error).to.equal(undefined)
      })
      readStream.on('data', function (data) {
        receivedBytes += data.length
      })
      readStream.on('finish', function () {
        expect(receivedBytes).to.equal(3774)
        done()
      })
    })
    

提交回复
热议问题