Passing a value from PhantomJS to node.js

≯℡__Kan透↙ 提交于 2019-12-03 12:32:06

问题


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
});

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/12979723/passing-a-value-from-phantomjs-to-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!