代码:
var casper = require('casper').create({
waitTimeout: 120000,
stepTimeout: 120000,
verbose: true,
logLevel: "debug"
});
var process = require("child_process")
var spawn = process.spawn
casper.start('http://baidu.com')
casper.then(function () {
casper.echo(httpCall('baidu.com', 'GET'))
})
function httpCall(url, method) {
var para = ["-X", method, url]
casper.log('curl with parameters: ' + para)
var child = spawn("curl", para)
var result = "abc"
child.stdout.on("data", function (data) {
casper.echo("curl ended.")
result = data;
})
return result;
}
casper.then(function () {
casper.wait(2000)
})
casper.run()
使用casperjs test_child_process.js
运行输出:
[info] [phantom] [2016-05-05T10:23:36.196Z] Starting...
[info] [phantom] [2016-05-05T10:23:36.203Z] Running suite: 4 steps
[debug] [phantom] [2016-05-05T10:23:36.226Z] opening url: http://baidu.com/, HTTP GET
[debug] [phantom] [2016-05-05T10:23:36.227Z] Navigation requested: url=http://baidu.com/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] [2016-05-05T10:23:36.461Z] Navigation requested: url=https://www.baidu.com/, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] [2016-05-05T10:23:36.684Z] url changed to "https://www.baidu.com/"
[debug] [phantom] [2016-05-05T10:23:37.364Z] Successfully injected Casper client-side utilities
[debug] [phantom] [2016-05-05T10:23:37.382Z] start page is loaded
[info] [phantom] [2016-05-05T10:23:37.406Z] Step anonymous 3/4 https://www.baidu.com/ (HTTP 200)
[debug] [phantom] [2016-05-05T10:23:37.406Z] curl with parameters: -X,GET,baidu.com
abc <- I want it to be the stdout of curl...
[info] [phantom] [2016-05-05T10:23:37.413Z] Step anonymous 3/4: done in 1216ms.
[info] [phantom] [2016-05-05T10:23:37.429Z] Step anonymous 4/4 https://www.baidu.com/ (HTTP 200)
[info] [phantom] [2016-05-05T10:23:37.430Z] Step anonymous 4/4: done in 1233ms.
[info] [phantom] [2016-05-05T10:23:37.451Z] Step _step 5/5 https://www.baidu.com/ (HTTP 200)
[info] [phantom] [2016-05-05T10:23:37.451Z] Step _step 5/5: done in 1254ms.
curl ended.
[info] [phantom] [2016-05-05T10:23:39.452Z] wait() finished waiting for 2000ms.
[info] [phantom] [2016-05-05T10:23:39.453Z] Done 5 steps in 3256ms
[debug] [phantom] [2016-05-05T10:23:39.455Z] Navigation requested: url=about:blank, type=Other, willNavigate=true, isMainFrame=true
[debug] [phantom] [2016-05-05T10:23:39.456Z] url changed to "about:blank"
我只是希望httpCall()
返回curl的stdout(这将浪费一些时间,但可以从许多回调中保存我们的遗留代码......),但我不知道该怎么做。可以有人给我一些建议吗?