| 296 | * @since 4.0.0 |
| 297 | */ |
| 298 | export const toString = <E = Cause.UnknownError>( |
| 299 | readable: LazyArg<Readable | NodeJS.ReadableStream>, |
| 300 | options?: { |
| 301 | readonly onError?: (error: unknown) => E |
| 302 | readonly encoding?: BufferEncoding | undefined |
| 303 | readonly maxBytes?: ByteSize.Input | undefined |
| 304 | readonly destroyOnOverflow?: boolean | undefined |
| 305 | } |
| 306 | ): Effect.Effect<string, E> => { |
| 307 | const maxBytesNumber = toMaxBytes(options?.maxBytes) |
| 308 | const onError = options?.onError ?? defaultOnError |
| 309 | const encoding = options?.encoding ?? "utf8" |
| 310 | return Effect.callback((resume) => { |
| 311 | const stream = readable() as Readable |
| 312 | // Decoding here keeps `maxBytes` on raw bytes. A stream that already |
| 313 | // decodes only emits strings, so switch it to `encoding` instead. |
| 314 | // Object-mode strings are not encoded bytes and count as UTF-8. |
| 315 | const decodes = stream.readableEncoding !== null |
| 316 | if (decodes) stream.setEncoding(encoding) |
| 317 | const decoder = new StringDecoder(encoding) |
| 318 | |
| 319 | let string = "" |
| 320 | let bytes = 0 |
| 321 | const cleanup = finished(stream, { readable: true, writable: false }, (err) => { |
| 322 | stream.off("data", onData) |
| 323 | if (err) { |
| 324 | destroyReadable(stream, cleanup) |
| 325 | resume(Effect.fail(onError(err) as E)) |
| 326 | } else { |
| 327 | cleanup() |
| 328 | resume(Effect.succeed(string + decoder.end())) |
| 329 | } |
| 330 | }) |
| 331 | function onData(chunk: string | Uint8Array) { |
| 332 | if (typeof chunk === "string") { |
| 333 | string += chunk |
| 334 | bytes += Buffer.byteLength(chunk, decodes ? encoding : "utf8") |
| 335 | } else { |
| 336 | string += decoder.write(chunk) |
| 337 | bytes += chunk.byteLength |
| 338 | } |
| 339 | if (maxBytesNumber !== undefined && bytes > maxBytesNumber) { |
| 340 | stream.off("data", onData) |
| 341 | if (options?.destroyOnOverflow === false) { |
| 342 | drainReadable(stream, cleanup) |
| 343 | } else { |
| 344 | destroyReadable(stream, cleanup) |
| 345 | } |
| 346 | resume(Effect.fail(onError(new MaxBytesError(maxBytesNumber)) as E)) |
| 347 | } |
| 348 | } |
| 349 | stream.on("data", onData) |
| 350 | return Effect.sync(() => { |
| 351 | stream.off("data", onData) |
| 352 | destroyReadable(stream, cleanup) |
| 353 | }) |
| 354 | }) |
| 355 | } |