Created
November 11, 2013 17:22
-
-
Save dylang/7416872 to your computer and use it in GitHub Desktop.
spawn as promised - use child_process.spawn as a q promise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var cp = require('child_process'); | |
var q = require('q'); | |
function spawn(command, args, options) { | |
var process; | |
var stderr = ''; | |
var stdout = ''; | |
var deferred = q.defer(); | |
process = cp.spawn(command, args, options); | |
process.stdout.on('data', function (data) { | |
data = data.toString(); | |
deferred.notify(data); | |
stdout += data; | |
}); | |
process.stderr.on('data', function (data) { | |
data = data.toString(); | |
deferred.notify(data); | |
stderr += data; | |
}); | |
// Listen to the close event instead of exit | |
// They are similar but close ensures that streams are flushed | |
process.on('close', function (code) { | |
var fullCommand; | |
var error; | |
if (code) { | |
// Generate the full command to be presented in the error message | |
if (!Array.isArray(args)) { | |
args = []; | |
} | |
fullCommand = command; | |
fullCommand += args.length ? ' ' + args.join(' ') : ''; | |
// Build the error instance | |
error = 'Failed to spawn "' + fullCommand + ' -- ' + stderr; | |
return deferred.reject(error); | |
} | |
return deferred.resolve([stdout, stderr]); | |
}); | |
return deferred.promise; | |
} | |
module.exports = spawn; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment