Skip to content

Commit

Permalink
phantomas.runScript: wait until it's finished
Browse files Browse the repository at this point in the history
Fixes #417
  • Loading branch information
macbre committed Nov 28, 2014
1 parent 8168dfb commit 45263e9
Showing 1 changed file with 34 additions and 25 deletions.
59 changes: 34 additions & 25 deletions core/phantomas.js
Original file line number Diff line number Diff line change
Expand Up @@ -761,9 +761,7 @@ phantomas.prototype = {
runScript: function(script, args, callback) {
var execFile = require("child_process").execFile,
start = Date.now(),
self = this,
pid,
ctx;
self = this;

if (typeof args === 'function') {
callback = args;
Expand All @@ -774,32 +772,43 @@ phantomas.prototype = {
args = args || [];
script = this.dir + script;

ctx = execFile(script, args, null, function(err, stdout, stderr) {
var time = Date.now() - start;
// always wait for runScript to finish (issue #417)
this.reportQueue.push(function(done) {
var ctx, pid;

ctx = execFile(script, args, null, function(err, stdout, stderr) {
var time = Date.now() - start;

if (err || stderr) {
self.log('runScript: pid #%d failed - %s (took %d ms)!', pid, (err || stderr || 'unknown error').trim(), time);
} else if (!pid) {
self.log('runScript: failed running %s %s!', script, args.join(' '));

done();
return;
} else {
self.log('runScript: pid #%d done (took %d ms)', pid, time);
}

// (try to) parse JSON-encoded output
try {
callback(null, JSON.parse(stdout));
} catch (ex) {
self.log('runScript: JSON parsing failed!');
callback(stderr, stdout);
}

done();
});

if (err || stderr) {
self.log('runScript: pid #%d failed - %s (took %d ms)!', pid, (err || stderr || 'unknown error').trim(), time);
} else if (!pid) {
self.log('runScript: failed running %s %s!', script, args.join(' '));
return;
} else {
self.log('runScript: pid #%d done (took %d ms)', pid, time);
}
pid = ctx.pid;

// (try to) parse JSON-encoded output
try {
callback(null, JSON.parse(stdout));
} catch (ex) {
self.log('runScript: JSON parsing failed!');
callback(stderr, stdout);
if (pid) {
self.log('runScript: %s %s (pid #%d)', script, args.join(' '), pid);
} else {
done();
}
});

pid = ctx.pid;

if (pid) {
this.log('runScript: %s %s (pid #%d)', script, args.join(' '), pid);
}
}
};

Expand Down

0 comments on commit 45263e9

Please sign in to comment.