Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a value from PhantomJS to node.js

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
});
like image 913
silkAdmin Avatar asked Oct 19 '12 17:10

silkAdmin


1 Answers

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.

like image 168
3on Avatar answered Nov 05 '22 11:11

3on