'Running npm inside AWS Lambda

I am trying to run npm install from inside AWS Lambda. But I'm getting the below error. Setting --prefix to "/tmp" doesn't work either.

{ Error: Command failed: npm install async npm ERR! code EROFS npm ERR! syscall mkdir npm ERR! path /home/sbx_user1051 npm ERR! errno -30 npm ERR! rofs EROFS: read-only file system, mkdir '/home/sbx_userXXXX' npm ERR! rofs Often virtualized file systems, or other file systems npm ERR! rofs that don't support symlinks, give this error.



Solution 1:[1]

You cannot run npm install inside lambda, you need to upload your modules using zip file

A deployment package is a ZIP archive that contains your function code and dependencies. You need to create a deployment package if you use the Lambda API to manage functions, or if you need to include libraries and dependencies other than the AWS SDK. You can upload the package directly to Lambda, or you can use an Amazon S3 bucket, and then upload it to Lambda. If the deployment package is larger than 50 MB, you must use Amazon S3.

https://docs.aws.amazon.com/lambda/latest/dg/nodejs-create-deployment-pkg.html

Solution 2:[2]

I was able to work around this same npm issue by creating a .zip, then an AWS Layer, then finally configuring the Lambda function to use that Layer; specific steps below:

  1. make a new empty directory: cd newdir && cd newdir

  2. install whatever npm things: npm install --save xyz

  3. make a directory skeleton that matches the expected Lambda structure for Node14 (there's a different structure for Node12, or various other languages; see https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html?icmpid=docs_lambda_help): mkdir -p nodejs/node14

  4. copy the "node_modules" directory into that newly made directory skeleton: cp -R node_modules nodejs/node14

  5. zip the whole thing up (name it whatever you want): zip -r custom-drivers-node14.zip nodejs

  6. from there, go to AWS console, Lambda, then "Layers" and create a new layer. In the dialog, upload your .zip file ("custom-drivers-node14.zip").

  7. finally, edit your Lambda function in AWS console, and add a new Layer – the interface might change, but as of now, this is under the main screen for a single function, then scroll way down to the bottom. Follow the "Add a layer" flow, choose the Layer you made, and then try your code.

One final note, this code structure worked:

const xyz = require('xyz');
exports.handler = async (event) => {
   xyz.doSomething();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 AWS PS
Solution 2 kaan