Skip to content
LogoLogo

@portable/lines

Classes

Lines.DecoderStream

A TransformStream that decodes bytes into lines of text, or splits text into lines.

class DecoderStream extends TransformStream<
  Uint8Array | string,
  string
> {
  constructor(options: DecoderStream.Options = {});
}
OptionTypeDefaultDescription
signalAbortSignalErrors the stream with signal.reason when aborted, which cancels the source it is piped from.
encodingstring'utf-8'Text encoding of byte chunks, as a TextDecoder label.
maxLengthnumberInfinityThe longest line, in UTF-16 code units, not counting the separator.
overflow"error" | "skip"'error'What to do with a line longer than maxLength: fail the stream, or drop the line and continue.
separatorSeparator/\r?\n/Where to split lines.
skipEmptybooleanfalseDrop empty lines instead of emitting them.
import * as Lines from '@portable/lines';
import * as Streams from '@portable/streams';
 
const response = await fetch('https://example.com/log.txt');
const lines = response.body!.pipeThrough(new Lines.DecoderStream());
for await (const line of Streams.toAsyncIterable(lines)) {
  console.log(line);
}

Errors

Lines.MaxLengthError

Thrown when a line grows past maxLength and overflow is 'error'.

class MaxLengthError extends Errors.MaxLengthError {
  constructor(options: Errors.MaxLengthError.Options);
  readonly kind: string;
}
import * as Lines from '@portable/lines';
import * as Streams from '@portable/streams';
 
const lines = response.body!.pipeThrough(
  new Lines.DecoderStream({ maxLength: 10_000 }),
);
try {
  for await (const line of Streams.toAsyncIterable(lines)) {
    console.log(line);
  }
} catch (error) {
  if (error instanceof Lines.MaxLengthError) {
    console.log(`a line exceeded ${error.maxLength}`);
  }
}

Types

Lines.Separator

Splits text into lines. A string matches literally, and anything with [Symbol.split], such as a RegExp, is used as is.

type Separator =
  | string
  | {
      [Symbol.split](text: string, limit?: number): string[];
    };