How to fetch/download/upload objects from S3 to AWS Lambda and vice versa in Node.js

In this tutorial, we will guide you on how to fetch S3 objects from your bucket to AWS lambda.

We won’t be getting in details in how to create a S3 bucket and a Lambda function, this tutorial assumes that you have already created both a Lambda function and a S3 bucket.

NOTE: This tutorial assumes that all the IAM policies related to bucket are public and lambda can establish a successful connection to the bucket.

Since there is not much to explain about the what’s and hows, we will directly just list down different boiler plate codes for possible cases, namely fetching URL,downloading an object and uploading an object to S3.

1) To fetch an object’s URL from S3.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {
 
  const params = {
    Bucket: `BUCKET_NAME_HERE`,
    Key: `directory_inside_bucket/myPDF.pdf`
  };
  
  try {
    await s3.headObject(params).promise();
    const url = s3.getSignedUrl('getObject', params);
    return url;
  }
  catch(error) {
    console.log(`Object not present/Unable to fetch ${error}`);
    
  }
}

This code fetches the object URL from ‘directory_inside_bucket/myPDF.pdf‘ and returns it.

Here we are fetching a PDF’s URL, you can fetch any object such as an image/document/video, etc.

2) To download an object into your local Lambda directory.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const fs = require('fs');

async function downloadObjects() {
  console.log("Starting Download")
  const params = {
    Bucket: 'BUCKET_NAME_HERE',
    Key: `directory_inside_bucket/myPDF.pdf`
   };

  await s3.getObject(params, (err, data) => {
    if(err) console.error(err);
    fs.writeFileSync(`/tmp/write_inside_lambda.pdf`, data.Body);
    console.log("Image Downloaded.");
  }).promise();
}

exports.handler = async (event, context, callback) => {
 await downloadOriginalCertificate();
}

The above code downloads the object from S3 bucket and writes it in lamda’s temporary directory. 

Note: You can only write to /tmp/xyzObject.abc inside lambda.


3) To upload an Object to your S3 bucket.

const AWS = require('aws-sdk');
const s3 = new AWS.S3();
const fs = require('fs');

async function uploadObject() {
  let filePath = `/tmp/.png`; //Specify the path of your object which you want to upload
  var params = {
    Bucket: 'YOUR_BUCKET_NAME',
    Body : fs.createReadStream(filePath),
    Key :  `BUCKET_PATH/original.png`,
    ContentType: 'image/png'
  };
  await s3.upload(params, function (err, data) {
    if (err) {
      console.log("Error", err);
    }
    if (data) {
      console.log("Uploaded in:", data.Location);
     
      } catch(err) {
        console.log(err);
      }
    }
  }).promise();
}

exports.handler = async (event, context, callback) => {
 await uploadObject();
}

In the above piece of code we are just uploading an object from our lambda to S3 bucket.

So we covered all three possibilities in this tutorial, if you found this useful / helpful please support the author by commenting 🙂

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top