从PhantomJS传递一个值到node.js
我有一个phantomJS脚本,通过node.js脚本中的exec()
调用执行。 现在我需要从PhantomJS脚本中返回一个string,以便它可以在节点中使用。
有没有办法做到这一点?
节点应用:
child = exec('./phantomjs dumper.js', function (error, stdout, stderr) { console.log(stdout, stderr); // Always empty });
dumper.js(幻影)
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 });
是的,只需使用JSON.stringify(result)
从PhantomJS输出一个JSONstring,然后使用JSON.parse(stdout)
在node.js中parsing它。
像这样的例子:
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(); });
这里是一些如何使用PhantomJS刮板的样板 。
更简单的方法(如果你有select的话)是使用NPM模块幻像而不是phantomjs 。 这允许您直接在nodejs中访问浏览器,而不是维护单独的脚本。