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