From 45263e977b9c92eb57c25cd188a467e5ba17d788 Mon Sep 17 00:00:00 2001 From: Maciej Brencz Date: Fri, 28 Nov 2014 21:01:43 +0100 Subject: [PATCH] phantomas.runScript: wait until it's finished Fixes #417 --- core/phantomas.js | 59 +++++++++++++++++++++++++++-------------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/core/phantomas.js b/core/phantomas.js index 19bc1c90a..7b2cca3d5 100644 --- a/core/phantomas.js +++ b/core/phantomas.js @@ -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; @@ -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); - } } };