node.js – 如何在具有NodeJS的AWS Lambda上运行PhantomJS

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

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

解决方法

以下是一个简单的PhantomJS进程的完整代码示例,它作为NodeJS child_process启动. It is also available on 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.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...