| 283 | * const { stdout } = await proc.result; |
| 284 | */ |
| 285 | export function execFileAsync( |
| 286 | file: string, |
| 287 | args: string[], |
| 288 | options?: ExecFileAsyncOptions |
| 289 | ): DisposableExec { |
| 290 | if (options?.signal?.aborted) { |
| 291 | const error = new Error("Command aborted before execution") as Error & { |
| 292 | code: number | null; |
| 293 | signal: string | null; |
| 294 | stdout: string; |
| 295 | stderr: string; |
| 296 | }; |
| 297 | error.code = null; |
| 298 | error.signal = null; |
| 299 | error.stdout = ""; |
| 300 | error.stderr = ""; |
| 301 | const result = Promise.reject(error); |
| 302 | void result.catch(() => undefined); |
| 303 | return new DisposableExec(result); |
| 304 | } |
| 305 | |
| 306 | const child = spawn(file, args, { |
| 307 | stdio: ["ignore", "pipe", "pipe"], |
| 308 | env: options?.env ? { ...process.env, ...options.env } : undefined, |
| 309 | }); |
| 310 | let timeoutHandle: ReturnType<typeof setTimeout> | undefined; |
| 311 | const cleanup = () => { |
| 312 | if (timeoutHandle) clearTimeout(timeoutHandle); |
| 313 | options?.signal?.removeEventListener("abort", onAbort); |
| 314 | }; |
| 315 | const killChild = () => { |
| 316 | if (child.exitCode === null && child.signalCode === null) { |
| 317 | child.kill(); |
| 318 | } |
| 319 | }; |
| 320 | const onAbort = () => killChild(); |
| 321 | if (options?.timeoutMs != null && options.timeoutMs > 0) { |
| 322 | timeoutHandle = setTimeout(killChild, options.timeoutMs); |
| 323 | timeoutHandle.unref?.(); |
| 324 | } |
| 325 | options?.signal?.addEventListener("abort", onAbort, { once: true }); |
| 326 | if (options?.signal?.aborted) { |
| 327 | onAbort(); |
| 328 | } |
| 329 | const promise = new Promise<{ stdout: string; stderr: string }>((resolve, reject) => { |
| 330 | let stdout = ""; |
| 331 | let stderr = ""; |
| 332 | let exitCode: number | null = null; |
| 333 | let exitSignal: string | null = null; |
| 334 | |
| 335 | child.stdout?.on("data", (data) => { |
| 336 | stdout += data; |
| 337 | }); |
| 338 | child.stderr?.on("data", (data: Buffer) => { |
| 339 | const chunk = data.toString(); |
| 340 | stderr += chunk; |
| 341 | options?.onStderrData?.(chunk); |
| 342 | }); |