[英]AWS Lambda: NodeJs custom layer
I'm new in nodejs and aws lambda.我是 nodejs 和 aws lambda 的新手。 I'm trying to create layer with common functions for my bunch of lambda functions.
我正在尝试为我的一堆 lambda 函数创建具有常用函数的层。 In lambda handler the import of custom module has the following definition:
let commonService = require('@common/service');
在 lambda 处理程序中,自定义模块的导入具有以下定义:
let commonService = require('@common/service');
The zip with the module file has the following structure:带有模块文件的 zip 结构如下:
nodejs
--node_modules
--@custom
--service
--index.js
--package.json
But I get the error: "errorMessage": "Error: Cannot find module '@common/service'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
但我收到错误:
"errorMessage": "Error: Cannot find module '@common/service'\nRequire stack:\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
The @custom/service module package.json contains the following: @custom/service模块 package.json 包含以下内容:
{
"name": "@common/service",
"version": "1.0.0",
"main": "index.js",
"license": "ISC",
"dependencies": {
/***
}
}
Thanks in advance!提前致谢!
Try using AWS Lambda Layers .尝试使用AWS Lambda 层。
Using Layers has two major benefits.使用图层有两个主要好处。
node_modules
folder hierarchy to upload every time.node_modules
文件夹层次结构。 How to use them?如何使用它们? It's a rather in-depth topic, but the gist of it is that you can:
这是一个相当深入的话题,但它的要点是您可以:
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
library in my CommonDependenciesLayer
, above.mysql
库放在上面的CommonDependenciesLayer
中。 As long as my Lambda function points to the layer in the SAM file, all I have to do is require('mysql')
in my code.require('mysql')
。 It'll be there. As you get it working, there are some subtleties to think about with respect to Layer deployment.当你开始工作时,有一些关于 Layer 部署的微妙之处需要考虑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.