2016-12-14 83 views
1

Iam與AWS LambdaNode.js一起玩。我創建了一個lambda函數並使用S3 event進行配置。 我想提取在S3上傳的zip文件,並將提取的文件上傳到同一個存儲桶中的另一個文件夾。使用帶有AWS Lambda函數的S3存儲桶從Node.js中提取zip文件並上傳到另一個存儲桶

我從下面的代碼中獲取存儲桶和文件信息,但之後我不知道如何提取並上傳到s3。

任何建議或大量的代碼將對我有幫助。

'use strict'; 

console.log('Loading function to get all latest object from S3 service'); 

const aws = require('aws-sdk'); 

const s3 = new aws.S3({ apiVersion: '2006-03-01' }); 


exports.handler = (event, context, callback) => { 
    console.log('Received event:', JSON.stringify(event, null, 2)); 

    // Get the object from the event and show its content type 
    const bucket = event.Records[0].s3.bucket.name; 
    const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); 
    const params = { 
     Bucket: bucket, 
     Key: key, 
    }; 
    s3.getObject(params, (err, data) => { 
     if (err) { 
      console.log(err); 
      const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; 
      console.log(message); 
      callback(message); 
     } else { 
      console.log('CONTENT TYPE:', data.ContentType); 
      callback(null, data); 
     } 
    }); 
}; 

回答

1

您可以使用zlib來解壓從s3獲得的緩衝區。

s3.getObject(params, (err, data) => { 
    if (err) { 
     console.log(err); 
     const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; 
     console.log(message); 
     callback(message); 
    } else { 
     zlib.gunzip(data.Body, function (err, result) { 
      if (err) { 
       console.log(err); 
      } else { 
       var extractedData = result; 
       s3.putObject({ 
       Bucket: "bucketName", 
       Key: "filename", 
       Body: extractedData, 
       ContentType: 'content-type' 
       }, function (err) { 
        console.log('uploaded file: ' + err); 
       }); 
      } 
     }); 
    } 
}); 

我覺得上面的函數可以幫到你。

+0

獲取錯誤'gunzip'錯誤'錯誤:不正確的標題檢查' – abdulbarik

+0

數據未壓縮時會引發此錯誤。 –

+1

我該如何解決這個錯誤?你能更新你的答案嗎? – abdulbarik

相關問題