-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
37 lines (32 loc) · 1.09 KB
/
utils.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
/**
* Executes shell command as it would happen in BASH script
* @param {string} command
* @param {Object} [options] Object with options. Set `capture` to TRUE, to capture and return stdout.
* Set `echo` to TRUE, to echo command passed.
* @returns {Promise<{code: number, data: string | undefined, error: Object}>}
*/
module.exports.exec = function (command, {capture = false, echo = false} = {}) {
if (echo) {
console.log(command);
}
const spawn = require('child_process').spawn;
const childProcess = spawn('bash', ['-c', command], {stdio: capture ? 'pipe' : 'inherit'});
return new Promise((resolve, reject) => {
let stdout = '';
if (capture) {
childProcess.stdout.on('data', (data) => {
stdout += data;
});
}
childProcess.on('error', function (error) {
reject({code: 1, error: error});
});
childProcess.on('close', function (code) {
if (code > 0) {
reject({code: code, error: 'Command failed with code ' + code});
} else {
resolve({code: code, data: stdout});
}
});
});
};