How to get contents of a text file from AWS S3 using a Lambda function with JavaScript?

Sometimes, we want to get contents of a text file from AWS S3 using a Lambda function with JavaScript.

In this article, we’ll look at how to get contents of a text file from AWS S3 using a Lambda function with JavaScript.

How to get contents of a text file from AWS S3 using a Lambda function with JavaScript?

To get contents of a text file from AWS S3 using a Lambda function with JavaScript, we use the getObject method.

For instance, we write

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

const handler = async (event, context) => {
  const Bucket = event.Records[0].s3.bucket.name;
  const Key = decodeURIComponent(
    event.Records[0].s3.object.key.replace(/+/g, " ")
  );
  const data = await s3.getObject({ Bucket, Key }).promise();
  console.log(data.Body.toString("ascii"));
};

to define the handler function.

In it, we get the Bucket1 and Key values from event.Records[0].

We replace the key’s slashes with spaces.

Then we call getObject to get the file by the Bucket and Key.

And then we get the file contents as a string with data.Body.toString.

Conclusion

To get contents of a text file from AWS S3 using a Lambda function with JavaScript, we use the getObject method.