How to get data from an json file in aws-lambda using node js

Viewed 1439

I am trying to read data from an json file in a lambda function using node js. Unable to retrieve the data. getting null response. My lambda function code as follows:

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
const s3 = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = async function(event, context, callback) {

    var bucketParams = {
        Bucket : 'sample-bucket',
        Key: 'employee.json'
    };

s3.getObject(bucketParams, function(err, data) {
    if (err) {
        console.log("Error", err);
    } else {
        callback(null, data.Body.toString());
    }
});

};

Response: null

1 Answers

Since you are returning using callback, you should not use asnyc:

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
const s3 = new AWS.S3({apiVersion: '2006-03-01'});

exports.handler = function(event, context, callback) {

    var bucketParams = {
        Bucket : 'sample-bucket',
        Key: 'employee.json'
    };

    s3.getObject(bucketParams, function(err, data) {
       if (err) {
          console.log("Error", err);
       } else {
        callback(null, data.Body.toString());
      }
    });

};

Also make sure that function has proper permissions an time to access S3.

Related