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.
Code
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:streamresolves 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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.