Streaming NDJSON Validated Parse

Stream newline-delimited JSON through a validating transform, quarantining malformed or schema-invalid lines while valid records flow on.

TypescriptData Fetching

Code

typescriptsnippet
54 lines
import { z } from 'zod';
import { Transform } from 'node:stream';
import { createReadStream } from 'node:fs';
import { pipeline } from 'node:stream/promises';

const RecordSchema = z.object({
  userId: z.number().int().positive(),
  event: z.string().min(1),
  at: z.string().datetime(),
});

class ValidatingLines extends Transform {
  private buffer = '';
  public valid = 0;
  public quarantined = 0;

  constructor() {
    super({ objectMode: true, readableObjectMode: false });
  }

  _transform(chunk: Buffer, _enc: string, callback: (err?: Error | null, data?: never) => void) {
    this.buffer += chunk.toString('utf8');
    let newline: number;

    while ((newline = this.buffer.indexOf('\n')) !== -1) {
      const line = this.buffer.slice(0, newline).trim();
      this.buffer = this.buffer.slice(newline + 1);
      if (!line) continue;

      try {
        const parsed = RecordSchema.parse(JSON.parse(line));
        this.valid += 1;
        this.push(JSON.stringify(parsed) + '\n');
      } catch {
        this.quarantined += 1;
      }
    }
    callback();
  }
}

const validator = new ValidatingLines();

await pipeline(
  createReadStream('events.ndjson'),
  validator,
  async function* (records) {
    for await (const line of records) {
      if (validator.valid % 100 === 0) console.log('streamed', validator.valid);
    }
  },
);

console.log('valid:', validator.valid, 'quarantined:', validator.quarantined);

How it works

Streaming NDJSON Validated Parse comes down to the class ValidatingLines.

Iteration is nested: while ((newline = this.buffer.indexOf('\n')) !== -1) frames the pass, for await (const line of records) does the per-item step. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import line is the dependency contract: z, Transform, createReadStream, pipeline come from zod and nothing else.

Top-level bindings RecordSchema, validator hold the demo state — nothing sits inside a function scope.

Caveats

  • Plan for an install step: zod is a real dependency, resolved by the package manager.
  • The guard !line short-circuits the flow with an early continue when its condition holds.

Using it

The demo output is labeled (streamed, valid:); each label names the call that printed it.

Key statements

this.push(JSON.stringify(parsed) + '\n');
this.buffer += chunk.toString('utf8');
for await (const line of records) {
  if (validator.valid % 100 === 0) console.log('streamed', validator.valid);
}

Interactive Tools for This Topic

FAQ

What does this need from the package registry?
These are real dependencies: `zod`. Without it the snippet will not load.