Get File From S3 bucket using Serverless and Node js

Viewed 10100

I am new to Serverless and AWS also. So My requirement is like. I need to download a file from S3. I have tried in many ways. I read many articles but could not find a proper document for this purpose.

So What I did was, I created a boilerplate using Serverless and got all the files like handler.js, serverless.yml

I need to know the correct steps to download a file from S3.

What I tried is. Handler.js

const AWS = require('aws-sdk');
const S3= new AWS.S3();
exports.hello = async (event, context) => {
  console.log(`Hi from Node.js ${process.version} on Lambda!`)
  S3.getObject({Bucket: '*******', Key: '******'}).promise().then( data =>{
    return {
      statusCode: 200,
      body: data
  })
}

Serveless.yml

service: node11

custom:
  bucket: *********

provider:
  name: aws
  runtime: provided # set to provided
  stage: dev
  region: us-east-1
  iamRoleStatements:
    - Effect: Allow
      Action:
        - s3:*
      Resource: "arn:aws:s3:::${self:custom.bucket}/*"

functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: /
          method: get
    layers: # add layer
      - arn:aws:lambda:us-east-1:553035198032:layer:nodejs11:3

Whatever I did, I am always getting an error like INTERNAL SERVER ERROR.

What is the proper way to get the file from S3?

1 Answers

Try this:

const AWS = require('aws-sdk');
const S3= new AWS.S3();
exports.hello = async (event, context) => {
  try {
    console.log(`Hi from Node.js ${process.version} on Lambda!`);
    // Converted it to async/await syntax just to simplify.
    const data = await S3.getObject({Bucket: '*******', Key: '******'}).promise();
    return {
      statusCode: 200,
      body: JSON.stringify(data)
    }
  }
  catch (err) {
    return {
      statusCode: err.statusCode || 400,
      body: err.message || JSON.stringify(err.message)
    }
  }
}

and ensure that in serverless.yml you've set runtime: nodejs8.10 under provider.

Lambda response body must be a string as defined here.

Related