How to synchronous call child process in CasperJS?

风流意气都作罢 提交于 2019-12-24 01:27:59

问题


Code:

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()

Run with casperjs test_child_process.js, the output:

[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"

I just want httpCall() returns the stdout of curl(That will waste some time, but could save our legacy codes from many callbacks...), but I have no idea how to do it. Could any one give me some advices?

来源:https://stackoverflow.com/questions/37048190/how-to-synchronous-call-child-process-in-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!