2016-12-14 84 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

相关问题