Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add external module in aws lambda function?

I have created a AWS Lambda Function , to putItem in dynamoDB table with API Gateway .

In the lambda function I have added a module for create userId UUID. I have Created Lambda function with inline code.

Now my problem is i am getting error , "Cannot find module 'uuid'"

Because Its a external module. So, Can anyone help me to figure out this issue. How I can I add this module in my lambda function and use it?

Below is my lambda function -

'use strict';
const uuid = require('uuid');
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB();

exports.handler = function(event, context) {

    var tableName = "SiplAwsAPI_users";
    var datetime = new Date().getTime().toString();

    dynamodb.putItem({
        "TableName": tableName,
        "Item": {
            "userId": {"S": uuid.v1()}, 
            "timedate": {"S": datetime},
            "userName": {"S": event.userName},
            "userPassword": {"S": event.userPassword},
        }
    }, function(err, data) {
        if (err) {
            var response= {"response":"false",                                                        "message":JSON.stringify(err.message, null, '  '),"data":JSON.stringify(err.statusCode, null, '  ')};
            context.succeed(response);
        } else {
            //console.log('Dynamo Success: ' + JSON.stringify(data, null, '  '));
            var response= {"response":"true", "message":"Register Successfully","data":JSON.stringify(data, null, '  ')};
            context.succeed(response);
        }
    });

}

Here is the error-

{
"errorMessage": "Cannot find module 'uuid'",
"errorType": "Error",
"stackTrace": [
"Function.Module._load (module.js:276:25)",
"Module.require (module.js:353:17)",
"require (internal/module.js:12:17)",
"Object.<anonymous> (/var/task/index.js:3:14)",
"Module._compile (module.js:409:26)",
"Object.Module._extensions..js (module.js:416:10)",
"Module.load (module.js:343:32)",
"Function.Module._load (module.js:300:12)",
"Module.require (module.js:353:17)"
]
}
like image 686
Rahul Gaikwad Avatar asked Jul 01 '26 08:07

Rahul Gaikwad


2 Answers

To include NPM dependencies, you need to use the upload functionality. For this you need to create a directory and zip it with all the dependencies included.

To simplify this process of devOps you can consider using serverless framework

like image 189
Ashan Avatar answered Jul 04 '26 01:07

Ashan


The code above works in Node.js 8.10 without having to upload module.

const uuidv4 = require('uuid/v4');
var userId = uuidv4();
like image 38
Daniel Barral Avatar answered Jul 04 '26 02:07

Daniel Barral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!