* Read file contents as a stream via exec.
(filePath: string, abortSignal?: AbortSignal)
| 342 | * Read file contents as a stream via exec. |
| 343 | */ |
| 344 | readFile(filePath: string, abortSignal?: AbortSignal): ReadableStream<Uint8Array> { |
| 345 | return new ReadableStream<Uint8Array>({ |
| 346 | start: async (controller: ReadableStreamDefaultController<Uint8Array>) => { |
| 347 | try { |
| 348 | const stream = await this.exec(`cat ${this.quoteForRemote(filePath)}`, { |
| 349 | cwd: this.getBasePath(), |
| 350 | timeout: 300, |
| 351 | abortSignal, |
| 352 | }); |
| 353 | |
| 354 | const reader = stream.stdout.getReader(); |
| 355 | const exitCodePromise = stream.exitCode; |
| 356 | |
| 357 | while (true) { |
| 358 | const { done, value } = await reader.read(); |
| 359 | if (done) break; |
| 360 | controller.enqueue(value); |
| 361 | } |
| 362 | |
| 363 | const code = await exitCodePromise; |
| 364 | if (code !== 0) { |
| 365 | const stderr = await streamToString(stream.stderr); |
| 366 | throw new RuntimeError(`Failed to read file ${filePath}: ${stderr}`, "file_io"); |
| 367 | } |
| 368 | |
| 369 | controller.close(); |
| 370 | } catch (err) { |
| 371 | if (err instanceof RuntimeError) { |
| 372 | controller.error(err); |
| 373 | } else { |
| 374 | controller.error( |
| 375 | new RuntimeError( |
| 376 | `Failed to read file ${filePath}: ${getErrorMessage(err)}`, |
| 377 | "file_io", |
| 378 | err instanceof Error ? err : undefined |
| 379 | ) |
| 380 | ); |
| 381 | } |
| 382 | } |
| 383 | }, |
| 384 | }); |
| 385 | } |
| 386 | |
| 387 | /** |
| 388 | * Write file contents atomically via exec. |