一尘不染

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

node.js

在互联网上其他任何地方都找不到有效的答案后,我将提交此“自问自答”教程

如何PhantomJSNodeJS脚本上运行一个简单的进程AWS Lambda?我的代码在本地计算机上运行良好,但是尝试在Lambda上运行时遇到了其他问题。


阅读 404

收藏
2020-07-07

共1个答案

一尘不染

这是一个简单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);
    });
}

phantom-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页面
并下载phantomjs-1.9.8-linux-x86_64.tar.bz2

2020-07-07