Recently I started with AWS Lambda functions, my Nodejs application was working well until I tried to use web3.js package. After I added the line
const Web3 = require('web3');
I got the error "Internal Server Error" for the HTTP endpoint, and the following in CloudWatch logs
module initialization error: Error
at Object.Module._extensions..node (module.js:681:18)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/var/task/node_modules/scrypt/index.js:3:20)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
Locally I have no issues to use web3.js package. So I started to dig deeper to understand what's wrong here. There are some native modules among dependencies. Some googling ends up with the idea that these packages should be compiled on Amazon Linux platform, otherwise it will not work. I started to create docker image to reach this goal.
Dockerfile
FROM amazonlinux:latest
# Install development tools
RUN yum update -y \
&& yum install gcc gcc44 gcc-c++ libgcc44 make cmake tar gzip git -y
# Install nvm and nodejs
RUN touch ~/.bashrc \
&& curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \
&& source ~/.bashrc \
&& nvm install v8.10
CMD source ~/.bashrc && npm install
Now in the root directory of my app I run the following command to install npm packages and compile native modules using docker image with Amazon Linux
docker run -it --rm -v $(pwd):/app -w /app docker/awslinuximage
I use serverless framework for deployment. In theory after deploy Lambda function should work, but in practice it doesn't. I found similar issues on Stackoverflow, but none helpful.
Moreover, I think this is a common problem for cloud functions to support Nodejs native modules, which should be compiled for specific OS.
Any idea and help to solve this issue appreciated. Thank you.