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