Deviopath › Node.js

Split a Stream into Lines

Medium · Streams

Node's readline module reads a stream chunk by chunk and emits a line event as soon as a full line is available. Write splitLines(chunks) that simulates this for an array of text chunks.

Return [{ line, chunk }] where chunk is the index of the chunk during which that line became complete.

- A line may be spread over several chunks, so keep a buffer.

- Lines end with \n or \r\n; the line text never includes them. The \r and \n may even arrive in different chunks, so the line only completes when the \n arrives.

- Empty lines in the middle are real lines ("").

- When the stream ends, leftover text without a newline is the last line, with chunk: "end". If the input ends with a newline, there is no extra empty line.

Simplification: unlike real readline, a lone \r (not followed by \n) is treated as a normal character.

Next: Count Words with for await