Transform Lines in a Readable Stream

Process a text stream line by line with a transform, keeping partial chunks buffered so splitting on newlines does not corrupt records.

JavascriptCli Tooling

Code

javascriptsnippet
21 lines
import { Transform } from "node:stream";

export function createLineTransformer(handler) {
  let buffer = "";
  return new Transform({
    transform(chunk, _encoding, callback) {
      buffer += chunk.toString("utf8");
      let index;
      while ((index = buffer.indexOf("\n")) !== -1) {
        const line = buffer.slice(0, index);
        buffer = buffer.slice(index + 1);
        this.push(handler(line) + "\n");
      }
      callback();
    },
    flush(callback) {
      if (buffer.length > 0) this.push(handler(buffer));
      callback();
    },
  });
}

How it works

The snippet is organized around the function createLineTransformer.

Repetition is confined to while ((index = buffer.indexOf("\n")) !== -1) — the rest of the file is straight-line. Transform comes from node:stream — Node.js core modules the runtime ships with.

The return value is newly constructed — inputs are never handed back.

What to watch for

  • node:stream resolves inside Node.js without any package — it is a core module.

Putting it to use

The main signature reads export function createLineTransformer(handler)

createLineTransformer is the public entry point; everything else in the file exists to support it.

Core lines

buffer += chunk.toString("utf8");

Interactive Tools for This Topic

FAQ

Does `createLineTransformer` modify its input?
No — a new value is constructed for the result and the arguments are never written to.
Is the imported module an npm package?
No — `node:stream` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.