【问题标题】:Stream PhantomJS output to frontend application将 PhantomJS 输出流式传输到前端应用程序
【发布时间】:2017-03-27 13:55:37
【问题描述】:

我有带有 PHP 后端的应用程序。我知道如何仅使用 PHP 从简单的 phantomjs 应用程序中获取输出。

$response = exec('/path/to/phantomjs myscript.js');

问题是……

我的 PhantomJS 应用程序工作很长时间(带有循环)并输出当前进度和进入脚本内部的操作以用于监控目的。

我需要做的是,

  1. 当用户按下某个按钮时执行 phantomjs 脚本
  2. 使用 php / websocket / html5 sse(服务器发送事件)流式传输它的输出,直到它完成

想法

我确信 PHP 不是用于此目的的合适选择,因为长轮询根本不是一种选择。

由于 websocket / html5 sse 的服务器推送支持,我认为其中之一将是合适的。

google了半天,找到了这个小应用https://github.com/joewalnes/websocketd

但不确定这是做我需要的正确方法。

不知道如何将 PhantomJS 应用程序的输出正确地流式传输到前端应用程序。

有什么建议吗?

【问题讨论】:

  • 那么你有没有想出一个解决方案?

标签: php html websocket phantomjs


【解决方案1】:

PhantomJS 有一个内置的服务器,这里是a nice answer about using it

但是如果你想使用 Websockets,它也是可行的,我个人发现使用 Express.js 和 Socket.io 是轻而易举的事。这是一个简短的概念代码:

var express = require("express");
var app = express();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var iosocket;

// save websocket connection for later use
io.on("connection", function(socket){
    iosocket = socket;
});

// GET request starts PhantomJS work, no matter how long
app.get("/launch-long-phantomjs-process", function(req, res){

    res.send("I'm on it!");

    var info = [];
    var spawn = require('child_process').spawn,
        child    = spawn('/usr/bin/phantomjs', ['/path/to/phantomjs/script.js']);

    console.log("Spawned parser");

    // Save incoming data from PhantomJS
    child.stdout.on('data', function (data) {
        console.log(data.toString());
        info.push(data.toString());
    });

    // Just in case of errors
    child.stderr.on('data', function (data) {
        console.log('stderr: ' + data);
    });

    // When PhantomJS exits, we can finally send
    // collected data to browser via a websocket
    child.on('close', function (code) {
        iosocket.emit("info", info);
    });    

});

在这个方案中,PhantomJS 只是通过console.log 将抓取的数据吐回节点。当然可以使用更复杂的方式来桥接 PhantomJS 和节点,例如 phantomjs-nodenode-phantomjs-simple

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 2012-01-20
    • 2017-04-29
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2014-11-11
    相关资源
    最近更新 更多