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