node-canvas build for AWS Lambda

流过昼夜 提交于 2019-12-05 18:24:14

I found this issue in the Node Canvas GitHub site. The questioner was trying to run FabricJS in Lambda as well. Here is the relevant section with an answer:

  1. Make sure you're compiling this on the same AMI that lambda currently uses: http://docs.aws.amazon.com/lambda/latest/dg/current-supported-versions.html

  2. Lambda runs at /var/task (that's the path when you unzip), so something.so at the root of the zip file will be at /var/task/something.so.

We then want to build our libraries using an "rpath":

   export LDFLAGS=-Wl,-rpath=/var/task/
  1. Compile libraries according to: https://github.com/Automattic/node-canvas/wiki/Installation---Amazon-Linux-AMI-%28EC2%29

You may want to set the prefix= ~/canvas to have all the files in one place.

  1. Install node-canvas with npm

  2. cd node_modules/canvas; node-gyp rebuild

  3. mkdir ~/pkg and cp the .so files (~/canvas/lib/*.so) there, using -L to dereference symlinks.

  4. scp the pkg directory to the local lambda folder, possibly putting the files in the right places. (.so in root, node_modules/canvas with other libs). You'll probably want to rearrange this.

Here is a gulp plugin which could upload your files along with node-canvas and its dependencies binary specifically built for aws lambda.

NPM Package

'use strict';
//This is a sample gulp file that can be used. 
//npm install --save gulp gulp-zip gulp-awslambda 
const gulp   = require('gulp');
const zip    = require('gulp-zip');
const path   = require('path');
const lambda = require('gulp-awslambda');
const aws_lambda_node_canvas = require('./');

let runtime = 'nodejs4.3' // nodejs or nodejs4.3 

const lambda_params  = {
    FunctionName: 'NodeCanvas', /* Lambda function name */
    Description: 'Node canvas function in aws lambda', //Description for your lambda function 
    Handler: 'main.lambda_handler', //Assuming you will provide main.py file with a function called handler. 
    MemorySize: 128,
    Runtime: runtime,
    Role : 'ROLE_STRING',//eg:'arn:aws:iam::[Account]:role/lambda_basic_execution' 
    Timeout: 50
};

var opts = {
    region : 'ap-southeast-2'
}

gulp.task('default', () => {
    return gulp.src(['main.js', '!node_modules/**/*','!dist/**/*','!node_modules/aws-lambda-node-canvas/**/*']) //Your src files to bundle into aws lambda 
        .pipe(aws_lambda_node_canvas({runtime : runtime})) //Adds all the required files needed to run node-canvas in aws lambda 
        .pipe(zip('archive.zip'))
        .pipe(lambda(lambda_params, opts))
        .pipe(gulp.dest('dist')); //Also place the uploaded file 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!