File size: 1,366 Bytes
b80fc11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import {
	type ChildProcess,
	type SpawnOptions,
	spawn,
} from "node:child_process";
import BufferList from "bl";

export const spawnAsync = (
	command: string,
	args?: string[] | undefined,
	onData?: (data: string) => void, // Callback opcional para manejar datos en tiempo real
	options?: SpawnOptions,
): Promise<BufferList> & { child: ChildProcess } => {
	const child = spawn(command, args ?? [], options ?? {});
	const stdout = child.stdout ? new BufferList() : new BufferList();
	const stderr = child.stderr ? new BufferList() : new BufferList();

	if (child.stdout) {
		child.stdout.on("data", (data) => {
			stdout.append(data);
			if (onData) {
				onData(data.toString());
			}
		});
	}
	if (child.stderr) {
		child.stderr.on("data", (data) => {
			stderr.append(data);
			if (onData) {
				onData(data.toString());
			}
		});
	}

	const promise = new Promise<BufferList>((resolve, reject) => {
		child.on("error", reject);

		child.on("close", (code) => {
			if (code === 0) {
				resolve(stdout);
			} else {
				const err = new Error(`${stderr.toString()}`) as Error & {
					code: number;
					stderr: BufferList;
					stdout: BufferList;
				};
				err.code = code || -1;
				err.stderr = stderr;
				err.stdout = stdout;
				reject(err);
			}
		});
	}) as Promise<BufferList> & { child: ChildProcess };

	promise.child = child;

	return promise;
};