Passing a value from PhantomJS to node.js

2019-03-15 22:00发布

I have a phantomJS script that is executed via an exec() call in a node.js script. Now I need to return a string from the PhantomJS script so that it can be utilized back in node.
Is there a way to achieve that ?

Node app:

child = exec('./phantomjs dumper.js',
    function (error, stdout, stderr) {
        console.log(stdout, stderr);      // Always empty
    });

dumper.js (Phantom)

var system = require('system');
var page = require('webpage').create();
page.open( system.args[1], function (status) {
    if (status !== 'success') {
        console.log('Unable to access the network!');
    } else {

        return "String"; // Doesn't work
    }
    phantom.exit('String2'); //Doesn't work either
});

2条回答
老娘就宠你
2楼-- · 2019-03-15 22:42

Much simpler way (if you have the option) is to use the NPM module phantom instead of phantomjs. This allows you to access the browser directly in nodejs instead of maintaining separate scripts.

查看更多
一纸荒年 Trace。
3楼-- · 2019-03-15 22:48

Yeah just output a JSON string from PhantomJS using JSON.stringify(result) and parse it in node.js with JSON.parse(stdout).

Like this for example:

Node.js:

child = exec('./phantomjs dumper.js',
    function (error, stdout, stderr) {
        console.log(stdout, stderr);      // Always empty
        var result = JSON.parse(stdout);
    }
);

PhantomJS:

var system = require('system');
var page = require('webpage').create();
page.open( system.args[1], function (status) {
    if (status !== 'success') {
        console.log('Unable to access the network!');
    } else {

        console.log(JSON.stringify({string:"This is a string", more: []}));
    }
    phantom.exit();
});

Here is some boilerplate for how to use PhantomJS to scrape.

查看更多
登录 后发表回答