在PhantomJS中调用shell命令

时间:2014-06-18 21:05:02

标签: javascript phantomjs casperjs headless-browser

我想知道如何在PhantomJS中运行shell命令,返回执行结果并将其分配给变量。

e.g。有一个phantomjs脚本:

var spawn = require("child_process").spawn
var execFile = require("child_process").execFile

var child = spawn("/usr/bin/php", ["script.php"])

child.stdout.on("data", function (data) {
  console.log(JSON.stringify(data))
})

和简单的PHP脚本:

<?php
echo "test";
?>

此示例仅打印到控制台&#34; test&#34;,但如何使用此返回的数据?是否可以将其分配给变量并在下一个PhantomJS步骤中使用它?

1 个答案:

答案 0 :(得分:0)

在这里http://phantomjs.org/api/child_process/并尝试&#34; process.execFile&#34;方法。 我成功了。

e.g。有一个phantomjs脚本:

var execFile = require("child_process").execFile;
execFile("php", ["a.php", 'bbb'], null, function (err, stdout, stderr) {
    console.log("execFileSTDOUT:", stdout);
    phantom.exit();
});

和简单的PHP脚本:

<?php print_r($argv); ?>

输出:

execFileSTDOUT: Array
(
    [0] => a.php
    [1] => bbb
)