Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Passing a value from PhantomJS to node.js

Passing a value from PhantomJS to node.js

Problem

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
});
Problem courtesy of: silkAdmin

Solution

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.

Solution courtesy of: 3on

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Passing a value from PhantomJS to node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×