How to load npm modules in AWS Lambda?

Fook picture Fook · Dec 23, 2015 · Viewed 99.4k times · Source

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.

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.

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

Answer

JohnAllen picture JohnAllen · Dec 23, 2015

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

Here's how:

  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.

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

  3. 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).

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

    zip -r lambdaFunc.zip .
    
  5. 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
    

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

  6. Now you can click test in the Lambda console.

  7. 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"