line-break-transformer.ts 652 B

1234567891011121314151617181920
  1. export class LineBreakTransformer implements Transformer<string, string> {
  2. private chunks = "";
  3. transform(
  4. chunk: string,
  5. controller: TransformStreamDefaultController<string>,
  6. ) {
  7. // Append new chunks to existing chunks.
  8. this.chunks += chunk;
  9. // For each line breaks in chunks, send the parsed lines out.
  10. const lines = this.chunks.split(/\r?\n/);
  11. this.chunks = lines.pop()!;
  12. lines.forEach((line) => controller.enqueue(line + "\r\n"));
  13. }
  14. flush(controller: TransformStreamDefaultController<string>) {
  15. // When the stream is closed, flush any remaining chunks out.
  16. controller.enqueue(this.chunks);
  17. }
  18. }