TypeScript
/**
* 서브프로세스 실행 헬퍼 (timeout, never-throw).
*/
import { type SpawnOptions, spawn, spawnSync } from "node:child_process";
export interface ExecResult {
stdout: string;
stderr: string;
code: number | null;
timedOut: boolean;
error: string | null;
wallTimeMs: number;
}
export function commandExists(bin: string): boolean {
try {
const r = spawnSync(process.platform === "win32" ? "where" : "which", [bin], {
stdio: "ignore",
});
return r.status === 0;
} catch {
return false;
}
}
export async function execCapture(
cmd: string,
args: string[],
opts: { cwd?: string; timeoutS: number; env?: NodeJS.ProcessEnv },
): Promise<ExecResult> {
const start = performance.now();
return new Promise<ExecResult>((resolve) => {
let stdout = "";
let stderr = "";
let timedOut = false;
let settled = false;
const so: SpawnOptions = {
cwd: opts.cwd,
env: { ...process.env, ...opts.env },
stdio: ["ignore", "pipe", "pipe"],
};
let child: ReturnType<typeof spawn>;
try {
child = spawn(cmd, args, so);
} catch (e) {
resolve({
stdout: "",
stderr: "",
code: null,
timedOut: false,
error: `spawn failed: ${(e as Error).message}`,
wallTimeMs: performance.now() - start,
});
return;
}
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, opts.timeoutS * 1000);
child.stdout?.on("data", (d) => {
stdout += d.toString();
});
child.stderr?.on("data", (d) => {
stderr += d.toString();
});
const finish = (code: number | null, error: string | null) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve({ stdout, stderr, code, timedOut, error, wallTimeMs: performance.now() - start });
};
child.on("error", (e) => finish(null, e.message));
child.on("close", (code) => finish(code, timedOut ? "timeout" : null));
});
}