Skip to content

Instantly share code, notes, and snippets.

@dylang
Created November 11, 2013 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylang/7416872 to your computer and use it in GitHub Desktop.
Save dylang/7416872 to your computer and use it in GitHub Desktop.
spawn as promised - use child_process.spawn as a q promise.
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