如何在AWS Lambda中加载npm模块?

问题描述:

我已经使用基于Web的编辑器创建了多个Lambda函数.到目前为止,一切都很好.我现在想开始使用模块(例如Q for promises)来扩展它们.我不知道如何将模块发布到Lambda,以便我的函数可以使用它们.

I've created several Lambda functions using the web based editor. So far so good. I'd now like to start extending those with modules (such as Q for promises). I can't figure out how to get the modules out to Lambda so they can be consumed by my functions.

我已阅读,但它似乎涉及设置EC2并从那里运行Lambda函数.创建函数时,有一种上传zip的机制,但这似乎包含发送本地开发的函数.由于我正在使用基于Web的编辑器,因此这似乎是一个奇怪的工作流程.

I've read through this but it seems to involve setting up an EC2 and running Lambda functions from there. There is a mechanism to upload a zip when creating a function but that seems to involve sending up functions developed locally. Since I'm working in the web based editor that seems like a strange workflow.

如何简单地部署一些模块以在Lambda函数中使用?

How can I simply deploy some modules for use in my Lambda functions?

您不能在不上传.zip文件的情况下加载NPM模块,但实际上可以将此过程简化为两个快速命令行.

You cannot load NPM modules without uploading a .zip file, but you can actually get this process down to two quick command lines.

方法如下:

  1. 将Lambda函数文件放在单独的目录中.这是因为您在本地为Lambda安装了npm软件包,并且希望能够隔离并测试要上传到Lambda的内容.

  1. Put your Lambda function file(s) in a separate directory. This is because you install npm packages locally for Lambda and you want to be able to isolate and test what you will upload to Lambda.

在步骤1中创建的单独Lambda目录中时,可使用npm install packageName在本地安装NPM软件包.

Install your NPM packages locally with npm install packageName while you're in your separate Lambda directory you created in step #1.

确保您的函数在本地运行时起作用:node lambdaFunc.js(您可以简单地注释掉代码中的两个export.handler行,以使您的代码在本地运行.)

Make sure your function works when running locally: node lambdaFunc.js (you can simply comment out the two export.handler lines in your code to adapt your code to run with Node locally).

转到Lambda的目录并压缩内容,确保包括目录本身.

Go to the Lambda's directory and compress the contents, make sure not to include the directory itself.

zip -r lambdaFunc.zip .

  • 如果您安装了aws-cli,如果您想让生活更轻松,我建议您安装它,现在可以输入以下命令:

  • If you have the aws-cli installed, which I suggest having if you want to make your life easier, you can now enter this command:

    aws lambda update-function-code --function-name lambdaFunc \
    --zip-file fileb://~/path/to/your/lambdaFunc.zip
    

    (上面的lambdaFunc部分周围没有引号,以防您像我一样怀疑)

    (no quotes around the lambdaFunc part above in case you wonder as I did)

    现在,您可以在Lambda控制台中单击 test .

    Now you can click test in the Lambda console.

    我建议为上述两个命令添加一个简短的别名.这是我对更长的Lambda update命令的看法:

    I suggest adding a short alias for both of the above commands. Here's what I have in mine for the much longer Lambda update command:

    alias up="aws lambda update-function-code --function-name lambdaFunc \
    --zip-file fileb://~/path/to/your/lambdaFunc.zip"