Dev1ce
Dev1ce

Reputation: 5944

Unable to upload npm dependencies on AWS Lambda Layer

I have a .zip file, which contains node_modules and a utils folders,
I upload the .zip on AWS Lambda Layer, but I am unable to fetch all the dependencies on the AWS Lambda function,

I believe the issues could be about the package.json, but
I tried deleting the node_modules, package-lock.json and reinstalling the dependencies using npm install command.
The dependencies seem to be downloaded on local but, when I upload them on Layers, they just disappear.

Root folder - enter image description here

Sub directories under layer folder - enter image description here

node_modules - enter image description here

package.json-

{
  "name": "serverless-currency",
  "version": "1.0.0",
  "description": "Lambda APIs for G2G Currency Module",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "debug": "SLS_DEBUG=* sls offline start"
  },
  "author": "Aniruddha Raje",
  "license": "ISC",
  "dependencies": {
    "async": "^2.6.2",
    "aws-sdk": "^2.447.0",
    "axios": "^0.18.0",
    "cryptr": "^4.0.2",
    "jsonwebtoken": "^8.5.1",
    "moment": "^2.24.0",
    "serverless-offline": "^4.9.4",
    "util": "^0.12.0"
  }
}

AWS Lambda code -

var fs = require('fs');
var async = require('async');

exports.handler = async (event) => {

    const testFolder = '/opt/layer/node_modules';

    fs.readdirSync(testFolder).forEach(file => {
  console.log(file);
});
};

Lambda error -

{
  "errorMessage": "Cannot find module 'async'",
  "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/index.js:2:13)",
    "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)"
  ]
}

Reference -
https://medium.com/@anjanava.biswas/nodejs-runtime-environment-with-aws-lambda-layers-f3914613e20e

Is it mandatory to name the root folder as nodejs so the node_module libs could be directly accessed using the let async = require('async') import,
So that the code doesn't need to specify the /opt/node_modules/async path?
The code ran without error when specified the absolute path.

Upvotes: 1

Views: 3306

Answers (1)

hoangdv
hoangdv

Reputation: 16147

You are wrong in your directory structure. In official document (here), you need a directory with a structure like layer/nodejs/node_modules, the nodejs directory name is not random and must be nodejs

layer
|
|__nodejs
     |
     |__node_modules
            |
            |__node_module1
            |
            |__async

Now you need to zip up the nodejs directory to nodejs.zip (or whatever what you want) and use this file to create your layer.

Upvotes: 6

Related Questions