Rahul Gaikwad
Rahul Gaikwad

Reputation: 589

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)"
]
}

Upvotes: 3

Views: 5278

Answers (3)

Daniel Barral
Daniel Barral

Reputation: 4096

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

const uuidv4 = require('uuid/v4');
var userId = uuidv4();

Upvotes: 1

semiadam
semiadam

Reputation: 91

If your AWS Lambda runtime is set to Node.js 6.10, uuid module will be loaded without having to upload a .zip. If your runtime is Node.js 4.3, you'll have to bundle uuid in your zip and upload.

Upvotes: 0

Ashan
Ashan

Reputation: 19728

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

Upvotes: 2

Related Questions