Wait for a child process in CasperJS

后端 未结 2 1016
挽巷
挽巷 2020-12-21 04:37

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 w

相关标签:
2条回答
  • 2020-12-21 05:08
    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(){});
    

    From my test, capser.run does not wait for execFile to finish the job. There is no log gets printed from the execFile callback. @Artjom B.

    0 讨论(0)
  • 2020-12-21 05:13

    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();
    
    0 讨论(0)
提交回复
热议问题