Invoking a file from AWS lambda handler.js?

Viewed 1253

I have node.js file(i.e.abc.js) which will give the output when i run in my node.js editor. I want to run the same file in AWS Lambda.For that, I created a lambda and moved abc.js to there. To run, it seems i need to implement my abc.js file in handler.js(i.e.in lambda way means callback etc).

Is there any way to trigger abc.js from handler.js rather than implementing again the same thing in handler.js?

Checked regarding the above usecase but didn't find much on google.

Updated

My abc.js file

var AWS = require('aws-sdk');
// Set the region 
AWS.config.update({
    region: "ap-south-1"
   });

// Create S3 service object
s3 = new AWS.S3();
var params= {};
 s3.listBuckets(params, bucketList);
function bucketList(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else   
  {   
        console.log(data)
  }
}

My handler.js in lambda and modifying it based on my interpretation of your answer.

exports.handler = async (event) => {
    const abc = require('./abc.js');
    // TODO implement
abc.bucketList();     
};

This is the error i am getting

Response:
{
  "errorMessage": "abc.bucketList is not a function",
  "errorType": "TypeError",
  "stackTrace": [
    "exports.handler (/var/task/index.js:5:5)"
  ]
}

Any help is appreciated.

3 Answers

Require your file

const abc = require('./abc.js');

And in the handler function call your code

abc.yourExportedMethod();

You have some issues inside of your abc.js file.

Try this snippet:

const abc = async function() 
{
    try
    {
        const AWS = require('aws-sdk');
        let s3 = new AWS.S3({region: "ap-south-1", apiVersion: '2006-03-01' });
        let params= {};
        const s3Response = await s3.listBuckets(params).promise();

        console.log(s3Response); // your list of buckets 

    }
    catch (ex)
    {
        console.error(ex);
    }
}

export default abc;

Add the following line at the bottom of your abc.js

exports.bucketList = bucketList

and the rest will work as you expect it to.

Related