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

25

在互联网上没有找到有效的答案之后,我决定自己发布这篇问答式教程。

我应该如何在AWS Lambda上从NodeJS脚本中运行一个简单的PhantomJS进程?我的代码在本地机器上运行良好,但是在Lambda上运行时遇到了不同的问题。

2个回答

31

编辑:这个方法不再有效这是一个明显的解决方法


这里是一个完整的代码示例,演示了一个简单的PhantomJS进程,它作为NodeJSchild_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);
    });
}

幽灵脚本.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();

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


1
太棒了,@Tyler 的回答。 - Dave Maple
@Tyler 在我实现代码的过程中,一切都很顺利,除了它在完成之前显示了进程退出的信息。我能知道是什么导致了这个问题吗? - Vikas
这个已经不再适用了。以下是更为实时的答案:https://dev59.com/xbTma4cB1Zd3GeqP_sTY#56843029 - Daniel Kaplan

5
一种通用的解决方案是使用一个 AWS Linux 机器来安装 npm 模块并将其传输到您的 Lambda 可执行文件中。以下是步骤:
  1. 启动 EC2 实例
  2. 通过 ssh 连接 EC2
  3. 安装 Node + npm
  4. 安装所需的 npm 模块
  5. 将它们压缩
  6. 使用 scp 命令将其传输到本地机器上
  7. 解压缩并复制到 Lambda 函数的 npm_modules 文件夹中(不要在本地执行 npm install!)
  8. 上传代码到 Lambda
这里有一个教程,其中包含进一步的资源链接: 为 AWS Lambda 编译 node 模块库 当 PhantomJS 是另一个节点模块(例如“node-webshot”)的依赖项时,也可以使用此方法。

1
谢谢。比被采纳的答案更有帮助。 - geotheory

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接