microsoft/vscode-react-native
Publicmirrored from https://github.com/microsoft/vscode-react-nativeAvailable
src/utils/node/childProcess.ts
70lines · modecode
| 1 | import * as child_process from "child_process"; |
| 2 | import Q = require("q"); |
| 3 | |
| 4 | export interface IExecResult { |
| 5 | process: child_process.ChildProcess; |
| 6 | outcome: Q.Promise<Buffer>; |
| 7 | } |
| 8 | |
| 9 | interface IExecOptions { |
| 10 | cwd?: string; |
| 11 | stdio?: any; |
| 12 | env?: any; |
| 13 | encoding?: string; |
| 14 | timeout?: number; |
| 15 | maxBuffer?: number; |
| 16 | killSignal?: string; |
| 17 | } |
| 18 | |
| 19 | interface ISpawnOptions { |
| 20 | cwd?: string; |
| 21 | stdio?: any; |
| 22 | env?: any; |
| 23 | detached?: boolean; |
| 24 | } |
| 25 | |
| 26 | interface ISpawnResult { |
| 27 | stdin: any; |
| 28 | stdout: any; |
| 29 | stderr: any; |
| 30 | outcome: Q.Promise<number>; |
| 31 | } |
| 32 | |
| 33 | export class ChildProcess { |
| 34 | public exec(command: string, options: IExecOptions = {}): IExecResult { |
| 35 | let outcome = Q.defer<Buffer>(); |
| 36 | |
| 37 | let execProcess = child_process.exec(command, options, (error: Error, stdout: Buffer, stderr: Buffer) => { |
| 38 | if (error) { |
| 39 | outcome.reject({ error: error, stderr: stderr}); |
| 40 | } else { |
| 41 | outcome.resolve(stdout); |
| 42 | } |
| 43 | }); |
| 44 | |
| 45 | return { process: execProcess, outcome: outcome.promise }; |
| 46 | } |
| 47 | |
| 48 | public execToString(command: string, options: IExecOptions = {}): Q.Promise<string> { |
| 49 | return this.exec(command).outcome.then(stdout => stdout.toString()); |
| 50 | } |
| 51 | |
| 52 | public spawn(command: string, args?: string[], options: ISpawnOptions = {}): ISpawnResult { |
| 53 | let outcome = Q.defer<number>(); |
| 54 | |
| 55 | let spawnedProcess = child_process.spawn(command, args, options); |
| 56 | spawnedProcess.once("error", (error: any) => { |
| 57 | outcome.reject({ error: error }); |
| 58 | }); |
| 59 | spawnedProcess.once("close", (code: number) => { |
| 60 | if (code === 0) { |
| 61 | outcome.resolve(code); |
| 62 | } |
| 63 | }); |
| 64 | |
| 65 | return { stdin: spawnedProcess.stdin, |
| 66 | stdout: spawnedProcess.stdout, |
| 67 | stderr: spawnedProcess.stderr, |
| 68 | outcome: outcome.promise }; |
| 69 | } |
| 70 | } |