[英]How do I run PhantomJS on AWS Lambda with NodeJS
After not finding a working answer anywhere else on the internet, I am submitting this ask-and-answer-myself tutorial 在互联网上的任何其他地方找不到工作答案后,我正在提交这个问答式自己的教程
How can I get a simple PhantomJS
process running from a NodeJS
script on AWS Lambda
? 如何从
AWS Lambda
上的NodeJS
脚本运行简单的PhantomJS
进程? My code works fine on my local machine, but I run into different problems trying to run it on Lambda. 我的代码在我的本地机器上工作正常,但是我遇到了尝试在Lambda上运行它的不同问题。
EDIT: This no longer works . 编辑: 这不再有效 。 This is an apparent solution .
这是一个明显的解决方案 。
Here is a complete code sample of a simple PhantomJS
process, which is launched as a NodeJS
child_process
. 下面是一个简单的完整代码示例
PhantomJS
过程,该过程作为发起NodeJS
child_process
。 It is also available on github . 它也可以在github上找到 。
index.js 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);
});
}
phantom-script.js 幻像的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();
To get a PhantomJS binary that works with Amazon's Linux machine's, go to the PhantomJS Bitbucket Page and download phantomjs-1.9.8-linux-x86_64.tar.bz2
. 要获得适用于亚马逊Linux机器的PhantomJS二进制文件,请访问PhantomJS Bitbucket页面并下载
phantomjs-1.9.8-linux-x86_64.tar.bz2
。
A generic solution is to use an actual AWS Linux machine to install the npm modules and transfer them to your lambda executable. 通用解决方案是使用实际的AWS Linux机器来安装npm模块并将它们传输到lambda可执行文件。 Here are the steps:
以下是步骤:
scp
scp
它们提取到本地计算机 Here is a tutorial with links to further resources: Compile node module libraries for AWS Lambda 这是一个教程,其中包含指向更多资源的链接: 为AWS Lambda编译节点模块库
This also works in such cases when PhantomJS is a dependency of another node module, eg. 当PhantomJS是另一个节点模块的依赖项时,这也适用于这种情况,例如。 node-webshot and you have less influence on what is being installed.
node-webshot,你对正在安装的内容影响较小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.