Writing to S3 from AWS Lambda

Sharing is Caring

AWS Lambda automatically includes the AWS SDK, so there’s no need to include it.

To write to Amazon S3 from an AWS Lambda function in Node.js, you can use the AWS SDK for JavaScript in Node.js.

Here is an example of how to write an object to S3:

const AWS = require('aws-sdk')

exports.handler = async (event, context) => {
  // Set the region 
  AWS.config.update({region: 'REGION'})

  // Create S3 service object
  const s3 = new AWS.S3({apiVersion: '2006-03-01'})

  // Set the bucket and key for the object.
  const params = {
    Bucket: 'BUCKET_NAME',
    Key: 'OBJECT_KEY',
    Body: 'OBJECT_CONTENTS'
  }

  // Write the object to S3
  try {
    const data = await s3.putObject(params).promise()
    console.log(data)
  } catch (err) {
    console.log(err)
  }
}

This example writes an object with the contents 'OBJECT_CONTENTS' to the bucket 'BUCKET_NAME' with the key 'OBJECT_KEY'. Make sure to replace 'REGION', 'BUCKET_NAME', and 'OBJECT_KEY' with the appropriate values for your environment.

Note that this example uses async/await syntax, which is only supported in Node.js versions 8.10 and later.

If you are using an earlier version of Node.js or prefer callbacks, you can use the .send method of the AWS.Request object instead.

I hope this helps! Let me know if you have any questions.

Sharing is Caring

Brian is a software architect and technology leader living in Niagara Falls with 13+ years of development experience. He is passionate about automation, business process re-engineering, and building a better tomorrow.

Brian is a proud father of four: two boys, and two girls and has been happily married to Crystal for more than ten years. From time to time, Brian may post about his faith, his family, and definitely about technology.