Skip to content

Alternative end stream handling #2

@robbiespeed

Description

@robbiespeed

Having null chunks in transform adds extra branch handling to simple transforms, and shouldn't be needed in the stateful transform API.

Alternatively if chunks was never null, you could do end handling with the stateful API by simply adding end logic after consuming the source.

Altered examples from the article:

const toUpperCase = (chunks) => chunks.map(chunk => {
  const str = new TextDecoder().decode(chunk);
  return new TextEncoder().encode(str.toUpperCase());
});

// Stateful transform with resource cleanup
function createGzipCompressor() {
  // Hypothetical compression API...
  const deflate = new Deflater({ gzip: true });

  return {
    async *transform(source) {
      for await (const chunks of source) {
        for (const chunk of chunks) {
          deflate.push(chunk, false);
          if (deflate.result) yield [deflate.result];
        }
      }
      // Flush: finalize compression
      deflate.push(new Uint8Array(0), true);
      if (deflate.result) return [deflate.result];
    },
    abort(reason) {
      // Clean up compressor resources on error/cancellation
    }
  };
}

Similarly I'm not sure if abort is necessary, could it be a try/catch inside transform instead?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions