在互联网上没有找到有效的答案之后,我决定自己发布这篇问答式教程。
我应该如何在AWS Lambda
上从NodeJS
脚本中运行一个简单的PhantomJS
进程?我的代码在本地机器上运行良好,但是在Lambda上运行时遇到了不同的问题。
在互联网上没有找到有效的答案之后,我决定自己发布这篇问答式教程。
我应该如何在AWS Lambda
上从NodeJS
脚本中运行一个简单的PhantomJS
进程?我的代码在本地机器上运行良好,但是在Lambda上运行时遇到了不同的问题。
编辑:这个方法不再有效。这是一个明显的解决方法。
这里是一个完整的代码示例,演示了一个简单的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);
});
}
幽灵脚本.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
。
scp
命令将其传输到本地机器上