Parse NDJSON from streaming response
Parse NDJSON from a streaming response by piping the body through a TransformStream that splits lines and parses each one as JSON.
NDJSON is one JSON value per line. A TransformStream can turn the byte stream into a stream of parsed objects, which you read with for await.
function ndjson() {
let buffer = '';
return new TransformStream({
transform(chunk, controller) {
buffer += chunk;
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) if (line.trim()) controller.enqueue(JSON.parse(line));
},
flush(controller) {
if (buffer.trim()) controller.enqueue(JSON.parse(buffer));
},
});
}
const encoder = new TextEncoder();
const res = new Response(
new ReadableStream({
start(c) {
c.enqueue(encoder.encode('{"id":1}\n{"i'));
c.enqueue(encoder.encode('d":2}\n'));
c.close();
},
}),
);
const objects = res.body.pipeThrough(new TextDecoderStream()).pipeThrough(ndjson());
for await (const obj of objects) console.log(obj);{ id: 1 }
{ id: 2 }The second line was split across two chunks, and the buffer joins the halves before parsing. flush runs when the input ends, which handles a last line with no trailing newline.
Iterating a ReadableStream with for await works in Node.js 18 and later, and in current Firefox and Chrome. In older Safari versions, read it with getReader() instead. Wrap JSON.parse in a try if the server may send a broken line and you want to keep going; as written, one bad line errors the stream. NDJSON is described at ndjson.org.