Node Stream Transform Chunk Pipeline

Chain readable, transform, and writable streams with pipeline to process large files in constant memory while propagating backpressure and errors.

JavascriptNodeFile Upload

Code

javascriptsnippet
32 lines
import { createReadStream, createWriteStream } from 'node:fs';
import { Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createGzip } from 'node:zlib';

class LineCount extends Transform {
  constructor() {
    super({ objectMode: false });
    this.lines = 0;
  }

  _transform(chunk, encoding, callback) {
    const text = chunk.toString('utf8');
    this.lines += (text.match(/\n/g) ?? []).length;
    this.push(text.toUpperCase());
    callback();
  }

  _flush(callback) {
    this.push('\n# total lines: ' + this.lines + '\n');
    callback();
  }
}

await pipeline(
  createReadStream('input.log', { encoding: 'utf8', highWaterMark: 64 * 1024 }),
  new LineCount(),
  createGzip({ level: 6 }),
  createWriteStream('output.log.gz'),
);

console.log('pipeline finished');

What the code does

Node Stream Transform Chunk Pipeline reduces to the class LineCount.

Await points sequence the asynchronous work; a rejection lands at the awaiting line. The only import source is node:fs, node:stream, node:stream/promises, a Node.js built-in, exposing createReadStream, createWriteStream, Transform, pipeline, createGzip.

Watch out for

  • node:fs is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

The demo output is labeled (pipeline finished), so every printed line maps back to its originating operation.

Statements that matter

this.lines += (text.match(/\n/g) ?? []).length;
await pipeline(
  createReadStream('input.log', { encoding: 'utf8', highWaterMark: 64 * 1024 }),
  new LineCount(),
  createGzip({ level: 6 }),
  createWriteStream('output.log.gz'),
);

Interactive Tools for This Topic

FAQ

What does this import from outside the project?
Only `node:fs`, and that is a Node.js built-in — it comes with the runtime.