QBoard » Supporting Tech Stack » Cloud » How to get contents of a text file from AWS s3 using a lambda function?

How to get contents of a text file from AWS s3 using a lambda function?

  • I was wondering if I could set up a lambda function for AWS, triggered whenever a new text file is uploaded into an s3 bucket. In the function, I would like to get the contents of the text file and process it somehow. I was wondering if this was possible...?

    For example, if I upload foo.txt, with contents foobarbaz, I would like to somehow get foobarbaz in my lambda function so I can do stuff with it. I know I can get metadata from getObject, or a similar method.

    Thanks!

      July 27, 2020 5:27 PM IST
    0
  • I am using lambda function with a python 3.6 environment. The code below will read the contents of a file main.txt inside bucket my_s3_bucket. Make sure to replace name of bucket and file name according to your needs.

    def lambda_handler(event, context):
        # TODO implement
        import boto3
    
        s3 = boto3.client('s3')
        data = s3.get_object(Bucket='my_s3_bucket', Key='main.txt')
        contents = data['Body'].read()
        print(contents)
     
      October 19, 2020 2:57 PM IST
    0
  • You can use data.Body.toString('ascii') to get the contents of the text file, assuming that the text file was encoded used ascii format. You can also pass other encoding types to the function. Check out Node-Buffer for further details.
      October 19, 2020 3:00 PM IST
    0