[英]Error: Cannot find module 'aws-sdk' in NodeJS AWS Lambda Function
I am trying to access S3
via aws-sdk
in my lambda function.我正在尝试通过我的 lambda function 中的
aws-sdk
访问S3
。
import S3 from 'aws-sdk/clients/s3';
const s3 = new S3();
const { Contents: results } = await s3.listObjects({ Bucket: process.env.DOCUMENTS_BUCKET_NAME! }).promise()
I have also deployed it successfully using cdk deploy
command.我还使用
cdk deploy
命令成功部署了它。 But when I test, I get the following error但是当我测试时,出现以下错误
2022-11-23T15:53:40.891Z undefined ERROR Uncaught Exception
{
"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:1000:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1035:21)",
" at async start (file:///var/runtime/index.mjs:1200:23)",
" at async file:///var/runtime/index.mjs:1206:1"
]
}
As per the documentation , aws-sdk
is always available in the runtime.根据文档,
aws-sdk
在运行时始终可用。
Does anyone know what am I doing wrong?有谁知道我做错了什么?
My attempt is available at https://github.com/hhimanshu/typescript-cdk/tree/module_5_lambda_api我的尝试可在https://github.com/hhimanshu/typescript-cdk/tree/module_5_lambda_api
Thank you very much非常感谢你
If your lambda runtime is nodejs18.x my understanding is that SDK v2 is not included in the runtime.如果您的 lambda 运行时是 nodejs18.x,我的理解是 SDK v2 不包含在运行时中。
So, the best solution would be to switch to v3 SDK https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/因此,最好的解决方案是切换到 v3 SDK https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/
Or, as a workaround in the short term if you use webpack and usually exclude bundling aws-sdk with the following:或者,作为短期的解决方法,如果您使用 webpack 并且通常不使用以下内容捆绑 aws-sdk:
externals: {
'aws-sdk': 'aws-sdk'
},
Then simply leave externals out of your webpack.config.js and it will be bundled, but will of course make your lambda larger so not ideal然后只需将 externals 排除在您的 webpack.config.js 之外,它就会被捆绑,但当然会使您的 lambda 更大,所以不理想
Or use nodejs16.x in the short term或者短期使用nodejs16.x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.