This repository was archived by the owner on Feb 9, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathchild-process.ts
94 lines (82 loc) · 2.29 KB
/
child-process.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import * as childProcess from "child_process";
export class ChildProcess {
public spawnFromEvent(command: string, args: string[], event: string, options?: ISpawnFromEventOptions): Promise<IProcessInfo> {
return new Promise<IProcessInfo>((resolve, reject) => {
options = options || {};
const commandChildProcess = childProcess.spawn(command, args, options.spawnOptions);
let capturedOut = "";
let capturedErr = "";
if (commandChildProcess.stdout) {
commandChildProcess.stdout.on("data", (data: string) => {
capturedOut += data;
});
}
if (commandChildProcess.stderr) {
commandChildProcess.stderr.on("data", (data: string) => {
capturedErr += data;
});
}
commandChildProcess.on(event, (arg: any) => {
const exitCode = typeof arg === "number" ? arg : arg && arg.code;
const result = {
stdout: capturedOut,
stderr: capturedErr,
exitCode: exitCode
};
if (options.ignoreError) {
resolve(result);
} else {
if (exitCode === 0) {
resolve(result);
} else {
let errorMessage = `Command ${command} failed with exit code ${exitCode}`;
if (capturedErr) {
errorMessage += ` Error output: \n ${capturedErr}`;
}
reject(errorMessage);
}
}
});
commandChildProcess.once("error", (err: Error) => {
if (options.ignoreError) {
const result = {
stdout: capturedOut,
stderr: err.message,
exitCode: (<any>err).code
};
resolve(result);
} else {
reject(err);
}
});
});
}
public exec(command: string, options?: childProcess.ExecOptions): Promise<IProcessInfo> {
return new Promise<IProcessInfo>((resolve, reject) => {
childProcess.exec(command, options, (err, stdout, stderr) => {
if (err) {
reject(err);
}
const result: IProcessInfo = {
stdout,
stderr
};
resolve(result);
});
});
}
public execSync(command: string, options?: childProcess.ExecSyncOptions): string {
return childProcess.execSync(command, options).toString();
}
public execFile(command: string, args: string[]): Promise<any> {
return new Promise<any>((resolve, reject) => {
childProcess.execFile(command, args, (error, stdout) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
}