Function toTransformStream

  • Convert the generator function into a TransformStream.

    Type Parameters

    • I
    • O

    Parameters

    • transformer: ((src: ReadableStream<I>) => Iterable<O, any, any> | AsyncIterable<O, any, any>)

      A function to transform.

        • (src): Iterable<O, any, any> | AsyncIterable<O, any, any>
        • Parameters

          • src: ReadableStream<I>

          Returns Iterable<O, any, any> | AsyncIterable<O, any, any>

    • OptionalwritableStrategy: QueuingStrategy<I>

      An object that optionally defines a queuing strategy for the stream.

    • OptionalreadableStrategy: QueuingStrategy<O>

      An object that optionally defines a queuing strategy for the stream.

    Returns TransformStream<I, O>

    A TransformStream that transforms the source stream as defined by the provided transformer.

    I The type of the chunks in the source stream.

    O The type of the chunks in the transformed stream.

    import { toTransformStream } from "@std/streams/to-transform-stream";
    import { assertEquals } from "@std/assert";

    const stream = ReadableStream.from([0, 1, 2])
    .pipeThrough(toTransformStream(async function* (src) {
    for await (const chunk of src) {
    yield chunk * 100;
    }
    }));

    assertEquals(
    await Array.fromAsync(stream),
    [0, 100, 200],
    );
    import { TextLineStream } from "@std/streams/text-line-stream";
    import { toTransformStream } from "@std/streams/to-transform-stream";
    import { assertEquals } from "@std/assert";

    const stream = ReadableStream.from([
    '{"name": "Alice", "age": ',
    '30}\n{"name": "Bob", "age"',
    ": 25}\n",
    ]);

    type Person = { name: string; age: number };

    // Split the stream by newline and parse each line as a JSON object
    const jsonStream = stream.pipeThrough(new TextLineStream())
    .pipeThrough(toTransformStream(async function* (src) {
    for await (const chunk of src) {
    if (chunk.trim().length === 0) {
    continue;
    }
    yield JSON.parse(chunk) as Person;
    }
    }));

    assertEquals(
    await Array.fromAsync(jsonStream),
    [{ "name": "Alice", "age": 30 }, { "name": "Bob", "age": 25 }],
    );