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

在互联网上的其他地方找不到工作答案之后,我正在提交这个问答本人教程

我如何从AWS Lambda上的NodeJS脚本获得一个简单的PhantomJS进程? 我的代码在我的本地机器上工作正常,但遇到了不同的问题,试图在Lambda上运行它。

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

幻像的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(); 

要获得与Amazon的Linux机器兼容的PhantomJS二进制文件,请转到PhantomJS Bitbucket Page并下载phantomjs-1.9.8-linux-x86_64.tar.bz2

通用的解决scheme是使用实际的AWS Linux机器来安装npm模块,并将它们传输到您的lambda可执行文件。 这里是步骤:

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

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

当PhantomJS是另一个节点模块的依赖时,这也适用于这种情况。 node-webshot,你对安装的东西影响较小。