Download image from S3 bucket to Lambda temp folder (Node.js)

[亡魂溺海] 提交于 2019-11-29 21:06:31

问题


Good day guys.

I have a simple question: How do I download an image from a S3 bucket to Lambda function temp folder for processing? Basically, I need to attach it to an email (this I can do when testing locally).

I have tried:

s3.download_file(bucket, key, '/tmp/image.png')

as well as (not sure which parameters will help me get the job done):

s3.getObject(params, (err, data) => {
    if (err) {
        console.log(err);
        const message = `Error getting object ${key} from bucket ${bucket}.`;
        console.log(message);
        callback(message);
    } else {

        console.log('CONTENT TYPE:', data.ContentType);
        callback(null, data.ContentType);
    }
});

Like I said, simple question, which for some reason I can't find a solution for.

Thanks!


回答1:


You can get the image using the aws s3 api, then write it to the tmp folder using fs.

var params = {   Bucket: "BUCKET_NAME",   Key: "OBJECT_KEY" };  

s3.getObject(params, function(err, data){   if (err) {
    console.error(err.code, "-", err.message);
    return callback(err);   }

  fs.writeFile('/tmp/filename', data.Body, function(err){
    if(err)
      console.log(err.code, "-", err.message);

    return callback(err);   
  }); 
});

Out of curiousity, why do you need to write the file in order to attach it? It seems kind of redundant to write the file to disk so that you can then read it from disk




回答2:


If you're writing it straight to the filesystem you can also do it with streams. It may be a little faster/more memory friendly, especially in a memory-constrained environment like Lambda.

var fs = require('fs');

var params = {
    Bucket: "mybucket",
    Key: "image.png"
};

var tempFileName = path.join('/tmp', 'downloadedimage.png');
var tempFile = fs.createWriteStream(tempFileName);

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


来源:https://stackoverflow.com/questions/38972739/download-image-from-s3-bucket-to-lambda-temp-folder-node-js

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