| 28 | |
| 29 | /** @internal */ |
| 30 | export const toString = <E>( |
| 31 | readable: LazyArg<Readable | NodeJS.ReadableStream>, |
| 32 | options: { |
| 33 | readonly onFailure: (error: unknown) => E |
| 34 | readonly encoding?: BufferEncoding | undefined |
| 35 | readonly maxBytes?: SizeInput | undefined |
| 36 | } |
| 37 | ): Effect.Effect<string, E> => { |
| 38 | const maxBytesNumber = options.maxBytes ? Number(options.maxBytes) : undefined |
| 39 | return Effect.acquireUseRelease( |
| 40 | Effect.sync(() => { |
| 41 | const stream = readable() |
| 42 | stream.setEncoding(options.encoding ?? "utf8") |
| 43 | return stream |
| 44 | }), |
| 45 | (stream) => |
| 46 | Effect.async((resume) => { |
| 47 | let string = "" |
| 48 | let bytes = 0 |
| 49 | stream.once("error", (err) => { |
| 50 | resume(Effect.fail(options.onFailure(err))) |
| 51 | }) |
| 52 | stream.once("end", () => { |
| 53 | resume(Effect.succeed(string)) |
| 54 | }) |
| 55 | stream.on("data", (chunk) => { |
| 56 | string += chunk |
| 57 | bytes += Buffer.byteLength(chunk) |
| 58 | if (maxBytesNumber && bytes > maxBytesNumber) { |
| 59 | resume(Effect.fail(options.onFailure(new Error("maxBytes exceeded")))) |
| 60 | } |
| 61 | }) |
| 62 | }), |
| 63 | (stream) => |
| 64 | Effect.sync(() => { |
| 65 | if ("closed" in stream && !stream.closed) { |
| 66 | stream.destroy() |
| 67 | } |
| 68 | }) |
| 69 | ) |
| 70 | } |
| 71 | |
| 72 | /** @internal */ |
| 73 | export const toUint8Array = <E>( |