-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathchild-process.ts
190 lines (162 loc) · 6.09 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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import * as child_process from "child_process";
import { EventEmitter } from "events";
export class ChildProcess extends EventEmitter implements IChildProcess {
constructor(private $logger: ILogger,
private $errors: IErrors) {
super();
}
public async exec(command: string, options?: any, execOptions?: IExecOptions): Promise<any> {
return new Promise<any>((resolve, reject) => {
const callback = (error: Error, stdout: string | NodeBuffer, stderr: string | NodeBuffer) => {
this.$logger.trace("Exec %s \n stdout: %s \n stderr: %s", command, stdout.toString(), stderr.toString());
if (error) {
reject(error);
} else {
const output = execOptions && execOptions.showStderr ? { stdout, stderr } : stdout;
resolve(output);
}
};
if (options) {
child_process.exec(command, options, callback);
} else {
child_process.exec(command, callback);
}
});
}
public async execFile(command: string, args: string[]): Promise<any> {
this.$logger.debug("execFile: %s %s", command, this.getArgumentsAsQuotedString(args));
return new Promise<any>((resolve, reject) => {
child_process.execFile(command, args, (error: any, stdout: string | NodeBuffer) => {
if (error) {
reject(error);
} else {
resolve(stdout);
}
});
});
}
public spawn(command: string, args?: string[], options?: any): child_process.ChildProcess {
this.$logger.debug("spawn: %s %s", command, this.getArgumentsAsQuotedString(args));
return child_process.spawn(command, args, options);
}
public fork(modulePath: string, args?: string[], options?: any): child_process.ChildProcess {
this.$logger.debug("fork: %s %s", modulePath, this.getArgumentsAsQuotedString(args));
return child_process.fork(modulePath, args, options);
}
public spawnFromEvent(command: string, args: string[], event: string,
options?: any, spawnFromEventOptions?: ISpawnFromEventOptions): Promise<ISpawnResult> { // event should be exit or close
return new Promise<ISpawnResult>((resolve, reject) => {
const childProcess = this.spawn(command, args, options);
let isResolved = false;
let capturedOut = "";
let capturedErr = "";
let killTimer: NodeJS.Timer = null;
if (spawnFromEventOptions && spawnFromEventOptions.timeout) {
this.$logger.trace(`Setting maximum time for execution of current child process to ${spawnFromEventOptions.timeout}`);
killTimer = setTimeout(() => {
this.$logger.trace(`Sending SIGTERM to current child process as maximum time for execution ${spawnFromEventOptions.timeout} had passed.`);
childProcess.kill('SIGTERM');
}, spawnFromEventOptions.timeout);
}
if (childProcess.stdout) {
childProcess.stdout.on("data", (data: string) => {
if (spawnFromEventOptions && spawnFromEventOptions.emitOptions && spawnFromEventOptions.emitOptions.eventName) {
this.emit(spawnFromEventOptions.emitOptions.eventName, { data, pipe: 'stdout' });
}
capturedOut += data;
});
}
if (childProcess.stderr) {
childProcess.stderr.on("data", (data: string) => {
if (spawnFromEventOptions && spawnFromEventOptions.emitOptions && spawnFromEventOptions.emitOptions.eventName) {
this.emit(spawnFromEventOptions.emitOptions.eventName, { data, pipe: 'stderr' });
}
capturedErr += data;
});
}
childProcess.on(event, (arg: any) => {
const exitCode = typeof arg === "number" ? arg : arg && arg.code;
const result = {
stdout: capturedOut,
stderr: capturedErr,
exitCode: exitCode
};
const clearKillTimer = () => {
if (killTimer) {
clearTimeout(killTimer);
}
};
const resolveAction = () => {
isResolved = true;
resolve(result);
clearKillTimer();
};
if (spawnFromEventOptions && spawnFromEventOptions.throwError === false) {
if (!isResolved) {
this.$logger.trace("Result when throw error is false:");
this.$logger.trace(result);
resolveAction();
}
} else {
if (exitCode === 0) {
resolveAction();
} else {
let errorMessage = `Command ${command} failed with exit code ${exitCode}`;
if (capturedErr) {
errorMessage += ` Error output: \n ${capturedErr}`;
}
if (!isResolved) {
isResolved = true;
reject(new Error(errorMessage));
clearKillTimer();
}
}
}
});
childProcess.once("error", (err: Error) => {
if (!isResolved) {
if (spawnFromEventOptions && spawnFromEventOptions.throwError === false) {
const result = {
stdout: capturedOut,
stderr: err.message,
exitCode: (<any>err).code
};
isResolved = true;
resolve(result);
} else {
isResolved = true;
reject(err);
}
}
});
});
}
public async trySpawnFromCloseEvent(command: string, args: string[], options?: any, spawnFromEventOptions?: ISpawnFromEventOptions): Promise<ISpawnResult> {
try {
const childProcess = await this.spawnFromEvent(command, args, "close", options, spawnFromEventOptions);
return childProcess;
} catch (err) {
this.$logger.trace(`Error from trySpawnFromCloseEvent method. More info: ${err}`);
return Promise.resolve({ stderr: err && err.message ? err.message : err, stdout: null, exitCode: -1 });
}
}
public async tryExecuteApplication(command: string, args: string[], event: string,
errorMessage: string, condition: (_childProcess: any) => boolean): Promise<any> {
const childProcess = await this.tryExecuteApplicationCore(command, args, event, errorMessage);
if (condition && condition(childProcess)) {
this.$errors.fail(errorMessage);
}
}
private async tryExecuteApplicationCore(command: string, args: string[], event: string, errorMessage: string): Promise<any> {
try {
return this.spawnFromEvent(command, args, event, undefined, { throwError: false });
} catch (e) {
const message = (e.code === "ENOENT") ? errorMessage : e.message;
this.$errors.failWithoutHelp(message);
}
}
private getArgumentsAsQuotedString(args: string[]): string {
return args && args.length && args.map(argument => `"${argument}"`).join(" ");
}
}
$injector.register("childProcess", ChildProcess);