-
Notifications
You must be signed in to change notification settings - Fork 5
/
promised-spawn.js
75 lines (60 loc) · 1.99 KB
/
promised-spawn.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// This code orginally from here, but modified to fit my needs.
//
// https://www.npmjs.com/package/promised-exec
//
'use strict';
var spawn = require('child_process').spawn
var Q = require('q');
var assert = require('chai').assert;
module.exports = function () {
return function (command, args, options) {
assert.isString(command);
if (args) {
assert.isArray(args);
}
else {
args = [];
}
if (options) {
assert.isObject(options);
}
options = options || {};
console.log("Running cmd: " + command + " " + args.join(' '));
return Q.Promise(function (resolve, reject) {
var stdout = '';
var stderr = ''
var cp = spawn(command, args, options);
cp.stdout.on('data', function (data) {
var str = data.toString();
//console.log(command + ':out: ' + str);
stdout += str;
});
cp.stderr.on('data', function (data) {
var str = data.toString();
//console.log(command + ':err: ' + str);
stderr += str;
});
cp.on('error', function (err) {
//console.log("Command failed: " + err.message);
reject(err);
});
cp.on('exit', function (code) {
//console.log('Command exited with code ' + code);
if (code === 0 || options.dontFailOnError) {
resolve({
code: code,
stdout: stdout,
stderr: stderr,
});
return;
}
var err = new Error('Command failed with code ' + code);
err.code = code;
err.stdout = stdout;
err.stderr = stderr;
reject(err);
});
});
};
};