|
1 | 1 | 'use strict' |
2 | 2 |
|
3 | | -const spawn = require('cross-spawn-promise') |
| 3 | +const spawn = require('cross-spawn') |
4 | 4 |
|
5 | 5 | /** |
6 | 6 | * Spawn a child process and make the error message more human friendly, if possible. |
7 | 7 | * |
| 8 | + * If logger is specified, it's usually a debug or console.log function pointer. |
8 | 9 | * Specify updateErrorCallback (a callback) to adjust the error object before it is rethrown. |
9 | 10 | */ |
10 | 11 | module.exports = async function (cmd, args, logger, updateErrorCallback) { |
11 | 12 | if (logger) logger(`Executing command ${cmd} ${args.join(' ')}`) |
12 | 13 |
|
13 | | - try { |
14 | | - const stdout = await spawn(cmd, args) |
15 | | - return stdout.toString() |
16 | | - } catch (err) { |
17 | | - const stderr = err.stderr ? err.stderr.toString() : '' |
18 | | - if (updateErrorCallback) { |
19 | | - updateErrorCallback(err, !!logger) |
20 | | - } |
21 | | - |
22 | | - throw new Error(`Error executing command (${err.message || err}):\n${cmd} ${args.join(' ')}\n${stderr}`) |
23 | | - } |
| 14 | + return new Promise((resolve, reject) => { |
| 15 | + let stdout = '' |
| 16 | + let stderr = '' |
| 17 | + const process = spawn(cmd, args) |
| 18 | + process.stdout.on('data', data => { |
| 19 | + stdout += data.toString() |
| 20 | + }) |
| 21 | + process.stderr.on('data', data => { |
| 22 | + /* istanbul ignore next */ |
| 23 | + stderr += data.toString() |
| 24 | + }) |
| 25 | + process.on('close', code => { |
| 26 | + if (code === 0) { |
| 27 | + resolve(stdout) |
| 28 | + } else { |
| 29 | + reject(new Error(`Command failed with a non-zero return code (${code}):\n${cmd} ${args.join(' ')}\n${stdout}\n${stderr}`)) |
| 30 | + } |
| 31 | + }) |
| 32 | + process.on('error', err => { |
| 33 | + if (updateErrorCallback) { |
| 34 | + updateErrorCallback(err, !!logger) |
| 35 | + } |
| 36 | + reject(new Error(`Error executing command (${err.message || err}):\n${cmd} ${args.join(' ')}\n${stderr}`)) |
| 37 | + }) |
| 38 | + }) |
24 | 39 | } |
0 commit comments