NDJSON Stream Parse Line By Line

Parse newline-delimited JSON from a stream line by line with error recovery and batch emission for large files.

JavascriptData Fetching

Code

javascriptsnippet
1 line
import{Transform}from'node:stream';export function ndjsonParser({batchSize=1}={}){let buffer='',batch=[];return new Transform({objectMode:true,transform(chunk,_,cb){buffer+=chunk.toString();const lines=buffer.split('\n');buffer=lines.pop()??'';for(const line of lines){if(line.trim()){try{batch.push(JSON.parse(line));}catch(e){cb(new Error('invalid JSON: '+line));return;}if(batch.length>=batchSize){this.push(batch);batch=[];}}}cb();},flush(cb){if(buffer.trim()){try{batch.push(JSON.parse(buffer));}catch(e){cb(e);return;}}if(batch.length>0)this.push(batch);cb();}});}

What the code does

The working surface is the function ndjsonParser — everything else is wiring.

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 is a Node.js built-in module — it ships with the runtime, so there is nothing to install.

Applying it

The primary signature is export function ndjsonParser({batchSize=1}={})

Callers only need ndjsonParser — everything else stays internal.

Interactive Tools for This Topic

FAQ

Does `ndjsonParser` modify its input?
No mutation happens — the function reads its input and returns a new value.
Are there third-party dependencies?
No. The imports resolve to Node.js core modules, which the runtime provides.