( command: string, args?: string[] | undefined, onData?: (data: string) => void, // Callback opcional para manejar datos en tiempo real options?: SpawnOptions, )
| 6 | import BufferList from "bl"; |
| 7 | |
| 8 | export const spawnAsync = ( |
| 9 | command: string, |
| 10 | args?: string[] | undefined, |
| 11 | onData?: (data: string) => void, // Callback opcional para manejar datos en tiempo real |
| 12 | options?: SpawnOptions, |
| 13 | ): Promise<BufferList> & { child: ChildProcess } => { |
| 14 | const child = spawn(command, args ?? [], options ?? {}); |
| 15 | const stdout = child.stdout ? new BufferList() : new BufferList(); |
| 16 | const stderr = child.stderr ? new BufferList() : new BufferList(); |
| 17 | |
| 18 | if (child.stdout) { |
| 19 | child.stdout.on("data", (data) => { |
| 20 | stdout.append(data); |
| 21 | if (onData) { |
| 22 | onData(data.toString()); |
| 23 | } |
| 24 | }); |
| 25 | } |
| 26 | if (child.stderr) { |
| 27 | child.stderr.on("data", (data) => { |
| 28 | stderr.append(data); |
| 29 | if (onData) { |
| 30 | onData(data.toString()); |
| 31 | } |
| 32 | }); |
| 33 | } |
| 34 | |
| 35 | const promise = new Promise<BufferList>((resolve, reject) => { |
| 36 | child.on("error", reject); |
| 37 | |
| 38 | child.on("close", (code) => { |
| 39 | if (code === 0) { |
| 40 | resolve(stdout); |
| 41 | } else { |
| 42 | const err = new Error(`${stderr.toString()}`) as Error & { |
| 43 | code: number; |
| 44 | stderr: BufferList; |
| 45 | stdout: BufferList; |
| 46 | }; |
| 47 | err.code = code || -1; |
| 48 | err.stderr = stderr; |
| 49 | err.stdout = stdout; |
| 50 | reject(err); |
| 51 | } |
| 52 | }); |
| 53 | }) as Promise<BufferList> & { child: ChildProcess }; |
| 54 | |
| 55 | promise.child = child; |
| 56 | |
| 57 | return promise; |
| 58 | }; |
no test coverage detected