Skip to content

Commit 8a9b8a1

Browse files
author
Mark Molinaro
committed
Attach the child process to the promise for more user control
1 parent 0c50ea0 commit 8a9b8a1

1 file changed

Lines changed: 11 additions & 9 deletions

File tree

execr.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import spawn from "cross-spawn";
22
import { memoize } from "lodash";
3-
import { SpawnOptions } from "child_process";
3+
import { SpawnOptions, ChildProcess } from "child_process";
44

55
type AnyKey<T> = T & {
66
[key: string]: T
@@ -25,8 +25,9 @@ type ExecResult = {
2525
stderr: string,
2626
}
2727

28+
type AttachedPromise<T> = Promise<T> & { _child: ChildProcess }
2829
type ExecFunction = (...args: ExecParameters) => ExecResult;
29-
type ExecAsyncFunction = (...args: ExecParameters) => Promise<ExecResult>;
30+
type ExecAsyncFunction = (...args: ExecParameters) => AttachedPromise<ExecResult>;
3031

3132
const memoizeSpawnSync = memoize(spawn.sync, (...args) => JSON.stringify(args));
3233
const isObject = (maybeObj: unknown) => Object.prototype.toString.call(maybeObj) == "[object Object]";
@@ -46,19 +47,17 @@ const normalizeArgs = (maybeArgs: MaybeArgs, options?: ExecOpts) => {
4647
return [finalArgs, finalOpts] as [string[], ExecOpts];
4748
}
4849

49-
async function execAsync(
50+
function execAsync(
5051
cmd: string,
5152
maybeArgs: MaybeArgs,
5253
opts?: ExecOpts
53-
): Promise<ExecResult> {
54+
): AttachedPromise<ExecResult> {
5455
const [endArgs, execOpts] = normalizeArgs(maybeArgs, opts);
5556

5657
let stdout = "";
5758
let stderr = "";
58-
59-
return new Promise(function (resolve, reject) {
60-
const childProcess = spawn(cmd, endArgs, execOpts);
61-
59+
const childProcess = spawn(cmd, endArgs, execOpts);
60+
const promise = new Promise(function (resolve, reject) {
6261
childProcess.stdout?.on("data", data => (stdout += data));
6362
childProcess.stderr?.on("data", data => (stderr += data));
6463

@@ -89,7 +88,10 @@ async function execAsync(
8988
stderr: `${stderr}`.trim()
9089
});
9190
});
92-
});
91+
}) as AttachedPromise<ExecResult>;
92+
93+
promise._child = childProcess;
94+
return promise;
9395
}
9496

9597
function exec(

0 commit comments

Comments
 (0)