| 34 | * @throws {ChildProcessError} |
| 35 | */ |
| 36 | export function spawnAsync( |
| 37 | command: string, |
| 38 | args: ReadonlyArray<string>, |
| 39 | options?: SpawnOptionsWithoutStdio, |
| 40 | ): Promise<{ stdout: string; stderr: string }> { |
| 41 | return new Promise((resolve, reject) => { |
| 42 | const process = spawn(command, args, { ...options, stdio: 'pipe' }); |
| 43 | |
| 44 | const stderr: Buffer[] = []; |
| 45 | const stdout: Buffer[] = []; |
| 46 | process.stderr.on('data', chunk => stderr.push(chunk)); |
| 47 | process.stdout.on('data', chunk => stdout.push(chunk)); |
| 48 | |
| 49 | const rejectWithError = (code?: number, innerError?: Error) => |
| 50 | reject( |
| 51 | new ChildProcessError( |
| 52 | command, |
| 53 | Buffer.concat(stderr).toString(), |
| 54 | Buffer.concat(stdout).toString(), |
| 55 | code, |
| 56 | innerError, |
| 57 | ), |
| 58 | ); |
| 59 | |
| 60 | process.on('error', err => rejectWithError(undefined, err)); |
| 61 | process.on('close', code => |
| 62 | code |
| 63 | ? rejectWithError(code) |
| 64 | : resolve({ |
| 65 | stdout: Buffer.concat(stdout).toString(), |
| 66 | stderr: Buffer.concat(stderr).toString(), |
| 67 | }), |
| 68 | ); |
| 69 | }); |
| 70 | } |