如何使用NodeJS在AWS Lambda上运行PhantomJS

Tyl*_*ler 24 amazon-web-services node.js phantomjs aws-lambda

在互联网上的任何其他地方找不到工作答案后,我正在提交这个问答式自己的教程

如何PhantomJSNodeJS脚本中运行简单的进程AWS Lambda?我的代码在我的本地机器上工作正常,但是我遇到了尝试在Lambda上运行它的不同问题.

Tyl*_*ler 30

这是一个简单PhantomJS过程的完整代码示例,它作为一个启动NodeJS child_process. 它也可以在github上找到.


index.js

var childProcess = require('child_process');
var path = require('path');

exports.handler = function(event, context) {

    // Set the path as described here: https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/
    process.env['PATH'] = process.env['PATH'] + ':' + process.env['LAMBDA_TASK_ROOT'];

    // Set the path to the phantomjs binary
    var phantomPath = path.join(__dirname, 'phantomjs_linux-x86_64');

    // Arguments for the phantom script
    var processArgs = [
        path.join(__dirname, 'phantom-script.js'),
       'my arg'
    ];

    // Launc the child process
    childProcess.execFile(phantomPath, processArgs, function(error, stdout, stderr) {
        if (error) {
            context.fail(error);
            return;
        }
        if (stderr) {
            context.fail(error);
            return;
        }
        context.succeed(stdout);
    });
}
Run Code Online (Sandbox Code Playgroud)

幻像的script.js

var system = require('system');
var args = system.args;

// Example of how to get arguments passed from node script
// args[0] would be this file's name: phantom-script.js
var unusedArg = args[1];

// Send some info node's childProcess' stdout
system.stdout.write('hello from phantom!')

phantom.exit();
Run Code Online (Sandbox Code Playgroud)

要获得适用于亚马逊Linux机器的PhantomJS二进制文件,请转到PhantomJS Bitbucket页面并下载phantomjs-1.9.8-linux-x86_64.tar.bz2.


Dav*_*mon 5

通用解决方案是使用实际的AWS Linux机器来安装npm模块并将它们传输到lambda可执行文件.以下是步骤:

  1. 启动EC2实例
  2. ssh进入EC2
  3. 安装Node + npm
  4. 安装所需的npm模块
  5. 拉上它们
  6. 用它们将它们提取到本地机器 scp
  7. 解压缩并复制到lambda函数的npm_modules文件夹(不要在本地安装npm!)
  8. 将您的代码上传到Lambda

这是一个教程,其中包含指向更多资源的链接: 编译AWS Lambda的节点模块库

当PhantomJS是另一个节点模块的依赖项时,这也适用于这种情况,例如.node-webshot,你对正在安装的内容影响较小.