Skip to content
jshacks.dev
APIs

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.

1 min read
Summarize in AI

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.

ndjson.jsJavaScript
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);
Text
{ 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.

Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read
APIs

Accept multipart upload in Node.js

Accept a multipart file upload in Node.js by wrapping the incoming request in a Request object and reading it with formData.

1 min read
Performance

Reduce JSON size by removing nulls

Drop null and undefined fields from an API payload with a JSON.stringify replacer, shrinking responses, and check clients treat a missing key like null.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.