node.jsamazon-web-servicesaws-lambdaserverless-application-model

SAM Node.js hello world app has axios module missing


I am new to both Node.js and SAM.

I am following the AWS Quick Start guide online here, except that I am using Node.js. Specifically, I ran these commands:

Versions:

▶ sam --version 
SAM CLI, version 0.10.0
▶ node --version                                                               
v8.15.0

Build:

▶ sam init --runtime nodejs
▶ cd sam-app/
▶ sam build
▶ sam package \
  --template-file template.yaml \
  --output-template-file packaged.yaml \
  --s3-bucket $s3_bucket
▶ sam deploy \
  --template-file packaged.yaml \
  --stack-name sam-app \
  --capabilities CAPABILITY_IAM

This all deploys the stack and the function fine, but it's then broken when I test it, because the axios module isn't there:

{
  "errorMessage": "Cannot find module 'axios'",
  "errorType": "Error",
  "stackTrace": [
    "Function.Module._load (module.js:474:25)",
    "Module.require (module.js:596:17)",
    "require (internal/module.js:11:18)",
    "Object.<anonymous> (/var/task/app.js:2:15)",
    "Module._compile (module.js:652:30)",
    "Object.Module._extensions..js (module.js:663:10)",
    "Module.load (module.js:565:32)",
    "tryModuleLoad (module.js:505:12)",
    "Function.Module._load (module.js:497:3)"
  ]
}

The Axios module does seem to be in the build directory however:

▶ ls -1 sam-app/.aws-sam/build/HelloWorldFunction/node_modules 
axios/
debug/
follow-redirects/
is-buffer/
ms/

But not in Lambda:

AWS Console

I've seen this other SO answer, but it doesn't help, because I thought SAM is supposed to package up all its dependencies.

Does anyone know what is wrong?


Solution

  • sam build will create sam-app artefact with node_modules. But when you do sam package with --template-file template.yaml, the artefact that is uploaded to s3 will not include the app dependencies because it packages your app according to the defined template file as opposed to the artefact you have built from sam build.

    You should remove the --template-file argument to the sam package command. Just do the following:

    sam build
    sam package --s3-bucket <your-bucket> --output-template-file packaged.yaml
    sam deploy \
      --template-file packaged.yaml \
      --stack-name sam-app \
      --capabilities CAPABILITY_IAM
    

    Now Lambda should be created with dependencies defined in package.json.