希望你一切顺利。我在设置的 lambda 上使用 lambda 层时遇到问题。到周日为止,我已经尝试了 6 种方法来解决这个问题,但没有任何效果。
我可以说这是一个相当典型的错误,因为我在这里、谷歌等上遇到了很多关于它的文章。无论如何,有一些东西让我无法理解,因为无论我如何应用这些解决方案,它们都不起作用。
请注意,我使用的是 Windows。
我遇到的错误是,
{
"errorType": "Runtime.ImportModuleError",
"errorMessage": "Error: Cannot find module 'aws-sdk'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/index.mjs",
"stack": [
"Runtime.ImportModuleError: Error: Cannot find module 'aws-sdk'",
"Require stack:",
"- /var/task/index.js",
"- /var/runtime/index.mjs",
" at _loadUserApp (file:///var/runtime/index.mjs:1061:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)",
" at async start (file:///var/runtime/index.mjs:1256:23)",
" at async file:///var/runtime/index.mjs:1262:1"
]
}
下面是 lambda 代码,尽管我认为它不会有帮助:
var AWS = require('aws-sdk');
AWS.config.update({region: 'US-East-1'})
var DynamoDBObject = new AWS.DynamoDB({apiVersion: '2012-08-10'})
exports.main = async function(event, context){
console.log(event['Details']['ContactData']['CustomerEndpoint']['Address'])
const numberNumber = parseInt(event['Details']['ContactData']['CustomerEndpoint']['Address'].replace("+1",""))
console.log("I\'m working! Look at me: ", numberNumber)
var params = {
TableName: '{MyTableName}',
Item: {
'PhoneNumber': numberNumber
}
}
DynamoDBObject.putItem(params, function(error, data){
if(error){
console.log("Error: ", error)
} else {
console.log("Success: ", data)
}
})
}
lambda 的架构/部署以及有关该层的信息(我在控制台中手动设置)位于此处:
import * as cdk from "aws-cdk-lib";
import { Construct } from "constructs";
import * as lambda from "aws-cdk-lib/aws-lambda";
import * as s3 from "aws-cdk-lib/aws-s3";
import path from "path";
export class LambdaService extends Construct {
constructor(scope: Construct, id: string){
super(scope, id);
//comment
const codeContainer = new s3.Bucket(this, "LambdaContainer")
const lambdaLayer = lambda.LayerVersion.fromLayerVersionArn(this, "mylambdalayer", "{LayerARN}")
new lambda.Function(this, "PhoneNumberInsert2", {
code: lambda.Code.fromAsset(path.join(__dirname,"../../Lambdas")),
runtime: lambda.Runtime.NODEJS_18_X,
handler: "index.main",
logRetention: 1,
description: "Lambda that enters a new phone number into DynamoDB",
environment: {
BUCKET: codeContainer.bucketName
},
layers:[lambdaLayer]
});
}
}
最后,当然,这是我在 AWS 中配置的层的文件结构。
**'TOP' Directory**: nodejs.zip
**Second Directory**: nodejs (why is it that when you zip, it adds this directory on top?)
**Third Directory Layer**:
1. Directory: 'node_modules'
2. File: package.json
3. File: package-lock.json
任何帮助将不胜感激。祝您度过愉快的一天!
如果您运行的是node18或更高版本,则默认情况下lambda运行时不再包含aws-sdk,而是具有@aws-sdk模块。如果是这种情况,您有几个选择: