MCPcopy Create free account
hub / github.com/Effect-TS/effect / toString

Function toString

packages/platform/node-shared/src/NodeStream.ts:298–355  ·  view source on GitHub ↗
(
  readable: LazyArg<Readable | NodeJS.ReadableStream>,
  options?: {
    readonly onError?: (error: unknown) => E
    readonly encoding?: BufferEncoding | undefined
    readonly maxBytes?: ByteSize.Input | undefined
    readonly destroyOnOverflow?: boolean | undefined
  }
)

Source from the content-addressed store, hash-verified

296 * @since 4.0.0
297 */
298export 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}

Callers

nothing calls this directly

Calls 11

toMaxBytesFunction · 0.85
readableFunction · 0.85
finishedFunction · 0.85
onErrorFunction · 0.70
cleanupFunction · 0.70
failMethod · 0.65
endMethod · 0.65
onMethod · 0.65
resumeFunction · 0.50
succeedMethod · 0.45
syncMethod · 0.45

Tested by

no test coverage detected