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.
Code
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:streamis 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
JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.NDJSON to JSON ConverterTurn newline-delimited JSON (JSON Lines) into a single JSON array, reporting the exact line where parsing fails.CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.