我是nodejs和aws lambda的新成员。我正在尝试为我的lambda函数创建一个具有公共函数的层。在lambda处理程序中,自定义模块的导入具有以下定义:let commonService = require('@common/service');
带有模块文件的zip具有以下结构:
nodejs
--node_modules
--@custom
--service
--index.js
--package.json
但是我得到了错误:"errorMessage": "Error: Cannot find module '@common/service'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
@定制/服务模块package.json包含以下内容:
{
"name": "@common/service",
"version": "1.0.0",
"main": "index.js",
"license": "ISC",
"dependencies": {
/***
}
}
提前感谢!
发布于 2021-01-14 14:04:07
尝试使用AWS Lambda层。
使用层有两个主要好处。
node_modules
文件夹层次结构来上传每次。如何使用它们?这是一个相当深入的话题,但最重要的是你可以:
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Description: My Serverless App
Parameters:
# ...
Globals:
Function:
Runtime: nodejs10.x
# Environment:
# Variables:
# NODE_ENV: test
Resources:
CommonDependenciesLayer:
Type: AWS::Serverless::LayerVersion
Properties:
LayerName: my-common-deps
Description: Common dependencies for my NodeJS apps
ContentUri: ../common-deps/
RetentionPolicy: Retain
Metadata:
BuildMethod: nodejs10.x
performSomeFunction:
Type: 'AWS::Serverless::Function'
Properties:
FunctionName: performSomeFunction
Handler: lambda.someFunction
Layers:
# You can either Ref a layer defined in this SAM file like this.
# - !Ref CommonDependenciesLayer
# ... or you can hard-code an external ARN
# - arn:aws:lambda:us-east-1:nnnnnnnnnnnnn:layer:myapp-common-deps:5
CodeUri: ./
# ...
mysql
库放在上面的CommonDependenciesLayer
中。只要我的Lambda函数指向SAM文件中的层,我所要做的就是代码中的require('mysql')
。它会在那里的。当您开始工作时,在层部署方面有一些需要考虑的微妙之处。
https://stackoverflow.com/questions/61638895
复制