Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

javascript - Wait for a child process in CasperJS

I have a CasperJS process that loads some page and then it needs to call a go-process to analyze the page and to decide what page should be loaded next. go-process takes a while to execute. My problem is that CasperJS doesn't wait for the go-process to complete and exits.

casper.then(function(){
  var p = cp.execFile('/path/parse', [], {}, function(error, stdout, stderr) {
    console.log(stdout);
  });

});

How can I wait for my child process to complete?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All then* and wait* functions are scheduling steps to be executed. When CasperJS runs out of steps to execute and no function is passed into casper.run(), then it will automatically exit.

The easy fix would be to always pass an empty function into casper.run() and schedule new steps from inside the function:

casper.then(function(){
  var p = cp.execFile('/path/parse', [], {}, function(error, stdout, stderr) {
    console.log(stdout);
    casper.thenOpen(parsedUrl).then(function(){
      // do something on page
    });
  });
});
casper.run(function(){});

A more clean approach would be to write your own step function that wraps the execFile function:

casper.waitForFileExec = function(process, callback, onTimeout, timeout){
    this.then(function(){
        var cp = require('child_process'),
            finished = false,
            self = this;
        timeout = timeout === null || this.options.stepTimeout;
        cp.execFile(process, [], {}, function(error, stdout, stderr) {
            finished = true;
            callback.call(self, error, stdout, stderr);
        });
        this.waitFor(function check(){
            return finished;
        }, null, onTimeout, timeout);
    });
    return this; // for builder/promise pattern
};

...
casper.waitForFileExec('/path/parse', function(error, stdout, stderr) {
    this.echo(stdout);
    this.thenOpen(parsedUrl).then(function(){
        // do something on page
    });
}).run();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...