繁体   English   中英

如何在aws lambda函数中添加外部模块?

[英]How to add external module in aws lambda function?

我创建了一个AWS Lambda函数,将putItem放在带有API网关的dynamoDB表中。

在lambda函数中,我添加了一个用于创建userId UUID的模块。 我使用内联代码创建了Lambda函数。

现在我的问题是我得到错误,“找不到模块'uuid'”

因为它是一个外部模块。 所以,任何人都可以帮我解决这个问题。 我如何在lambda函数中添加此模块并使用它?

下面是我的lambda函数 -

'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);
        }
    });

}

这是错误 -

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

要包含NPM依赖项,您需要使用上载功能。 为此,您需要创建一个目录并将其压缩,并包含所有依赖项。

要简化devOps的此过程,您可以考虑使用无服务器框架

上面的代码在Node.js 8.10中工作,无需上传模块。

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

如果您的AWS Lambda运行时设置为Node.js 6.10,则无需上载.zip即可加载uuid模块。 如果你的运行时是Node.js 4.3,你必须在你的zip中捆绑uuid并上传。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM