Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 3x 3x 1x 1x 3x 3x 3x | import { spawn, type SpawnOptionsWithoutStdio } from 'child_process';
import type { XExecResult } from './XUtil';
export type ExecutableOptions = SpawnOptionsWithoutStdio & {
onStdOut?: (m: string) => void;
onStdErr?: (m: string) => void;
};
/**
* Executes a shell command and streams its output.
*
* The {@link Executable} class uses Node.js's {@link child_process.spawn} to run
* a given command. It collects the standard output and error streams,
* optionally forwards the data through callbacks provided in the options
* object, and resolves a promise once the child process exits.
*
* @class
*/
export class Executable {
cmd: string;
options?: ExecutableOptions;
constructor(cmd: string, options?: ExecutableOptions) {
this.cmd = cmd;
this.options = options;
}
/**
* Executes the command specified by {@link cmd} with optional arguments and options.
*
* @param {string[]} [args] - Optional array of arguments to pass to the command.
* @returns {Promise<XExecResult>} A promise that resolves when the child process exits. The resolved value includes the exit code, a boolean indicating whether an error occurred, and the collected `stdout` and `stderr` output.
*/
async run(args?: string[]) {
return new Promise<XExecResult>((resolve) => {
const child = spawn(this.cmd, args, this.options);
let stdout = '';
let stderr = '';
Eif (child.stdout) {
child.stdout.on('data', (data) => {
stdout += data;
this.options?.onStdOut?.(data);
});
}
Eif (child.stderr) {
child.stderr.on('data', (data) => {
stderr += data;
this.options?.onStdErr?.(data);
});
}
child.on('close', (code) => {
const out: XExecResult = {
exitCode: code,
error: code !== 0,
stdout,
stderr,
};
resolve(out);
});
});
}
}
|