Stream NDJSON with JavaScript: Read Large API Exports One Record at a Time

How many units are in stock across a large inventory export? With an API that returns one JSON array, await response.json() waits for the entire body before you can count the first item. If the API can send one JSON value per line, the browser can update a running total as each record arrives. It only needs to keep the current record and two counters.
Give each record its own line
Save these three lines as sample.ndjson in an empty directory. Include a newline after the last record. We’ll build a browser example in the same directory and check that it reports 3 records, 25 units.
{"id":"9007199254740993","name":"Mug","quantity":12}
{"id":"9007199254740994","name":"Notebook","quantity":5}
{"id":"9007199254740995","name":"Café","quantity":8}
There are no commas between records or brackets around the export. The NDJSON specification calls for UTF-8 and a newline after each JSON value. Readers must accept both LF and CRLF. A newline inside a product name must appear as the JSON escape \n.
Keep the IDs quoted. The first one is just above JavaScript’s safe integer range, where parsing an ID as a number can silently change it. Our guide to duplicate keys and long JSON IDs shows how to spot the problem on an individual line.
Decode bytes first, then find the newlines
A network chunk could contain all three products, half a product, or just the first byte of the é in Café. There are two boundaries to recover. TextDecoderStream carries incomplete UTF-8 characters into the next read. Our generator carries the unfinished line into the next decoded chunk. Save it as ndjson.mjs.
// Parse a UTF-8 byte stream without assuming a chunk is a record.
export async function* readNDJSON(body, maxLine = 65536) {
if (!body) throw new Error('Missing response body');
if (!Number.isSafeInteger(maxLine) || maxLine < 1) {
throw new RangeError('Invalid line limit');
}
// The decoder keeps incomplete multi-byte characters between chunks.
const decoder = new TextDecoderStream('utf-8', { fatal: true });
const reader = body.pipeThrough(decoder).getReader();
let pending = '';
let lineNo = 1;
let finished = false;
try {
while (true) {
const { value, done } = await reader.read();
if (done) {
// Our strict producer contract requires a final newline.
if (pending.length) throw new Error(`Missing newline on line ${lineNo}`);
finished = true;
return;
}
let start = 0;
while (start < value.length) {
const end = value.indexOf('\n', start);
const stop = end === -1 ? value.length : end;
if (pending.length + (stop - start) > maxLine) {
throw new Error(`Line ${lineNo} too long`);
}
// Only join the pieces that make up this particular line.
pending += value.slice(start, stop);
// Preserve an unfinished line until the next network chunk.
if (end === -1) break;
// Accept LF and CRLF, and ignore genuinely empty lines.
const line = pending.endsWith('\r') ? pending.slice(0, -1) : pending;
pending = '';
start = end + 1;
if (line.includes('\r')) throw new Error(`Unexpected CR on line ${lineNo}`);
if (line.length) {
let record;
try {
record = JSON.parse(line);
} catch {
// Do not leak potentially sensitive record contents into logs.
throw new Error(`Invalid JSON on line ${lineNo}`);
}
yield record;
}
lineNo++;
}
}
} finally {
try {
// Cancel upstream if parsing fails or the consumer stops early.
if (!finished) await reader.cancel();
} finally {
reader.releaseLock();
}
}
}
The reader accepts empty lines, counts them for error messages and rejects whitespace-only lines as invalid JSON. It also rejects an unterminated final record. The example caps each raw line at 65,536 UTF-16 code units, including a possible carriage return. A server handling untrusted inputs still needs byte and time limits. The browser has already received a chunk by the time the parser examines it.
If a record is malformed or the caller breaks out of the loop, finally cancels the reader and releases its lock. With fatal: true, malformed UTF-8 also stops the import. For an example of a decoding error that does produce readable characters, see our UTF-8 troubleshooting guide.
Validate inventory fields before adding quantities
null is a perfectly valid NDJSON record. It doesn’t tell us how many mugs are in stock. Append these functions to ndjson.mjs to check the HTTP response and validate each item before counting it.
// Validate application fields separately from JSON syntax.
export function isItem(item) {
return item !== null && typeof item === 'object' && !Array.isArray(item)
&& typeof item.id === 'string' && /^\d{1,40}$/.test(item.id)
&& typeof item.name === 'string' && item.name.length <= 200
&& Number.isSafeInteger(item.quantity) && item.quantity >= 0;
}
export async function summarize(url, signal) {
const response = await fetch(url, {
headers: { Accept: 'application/x-ndjson' }, signal
});
// Ignore media type parameters such as charset when checking the response.
const type = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
if (!response.ok || type !== 'application/x-ndjson') {
await response.body?.cancel();
throw new Error(response.ok ? 'Unexpected content type' : `HTTP ${response.status}`);
}
let count = 0;
let units = 0n;
for await (const item of readNDJSON(response.body)) {
if (!isItem(item)) throw new Error(`Invalid item ${count + 1}`);
if (++count > 100000) throw new Error('Too many records');
// Keep an exact sum without accumulating the entire dataset.
units += BigInt(item.quantity);
}
return { count, units };
}
This inventory accepts decimal-string IDs, names up to 200 code units and nonnegative safe integer quantities. The example stops after 100,000 records. Each quantity fits in a JavaScript Number, but their sum might not. BigInt keeps the total exact. Convert it to a decimal string if you later send it in JSON.
Native JSON.parse() resolves duplicate object keys before the validator sees them. If your import must reject duplicates, use a parser that detects them while reading the original JSON. For an authoritative inventory, also check an expected count or checksum from the producer. A response cut short just after a newline can look like a complete, shorter export.
Put cancellation in the reader’s hands
Save this as index.html. The two buttons share one active request. Cancel aborts the Fetch, and the status region gives the final result without adding a DOM node for every product.
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Inventory summary</title>
<h1>Inventory summary</h1>
<button id="start">Load inventory</button>
<button id="stop" disabled>Cancel</button>
<p id="status" role="status">Ready.</p>
<script type="module">
import { summarize } from './ndjson.mjs';
const start = document.querySelector('#start');
const stop = document.querySelector('#stop');
const status = document.querySelector('#status');
// Keep one controller for the active request.
let controller;
start.addEventListener('click', async () => {
controller = new AbortController();
// Prevent a second request from replacing the active controller.
start.disabled = true;
stop.disabled = false;
status.textContent = 'Reading inventory...';
try {
const { count, units } = await summarize('./sample.ndjson', controller.signal);
status.textContent = `${count} records, ${units} units.`;
} catch (error) {
status.textContent = controller.signal.aborted ? 'Cancelled.' : 'Unable to read inventory.';
console.error(error.message);
} finally {
// Restore the controls after success, cancellation or failure.
start.disabled = false;
stop.disabled = true;
controller = undefined;
}
});
stop.addEventListener('click', () => controller?.abort());
</script>
</html>
Serve the sample with its actual media type
Save the following as server.mjs. It serves only the three demo files on the loopback interface and sends the media type that summarize() expects.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
// Map each public URL to the file and media type the browser should receive.
const routes = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
['/ndjson.mjs', ['ndjson.mjs', 'text/javascript']],
['/sample.ndjson', ['sample.ndjson', 'application/x-ndjson']]
]);
createServer(async (req, res) => {
const route = routes.get(req.url);
if (!route) {
res.writeHead(404).end();
return;
}
const [file, type] = route;
try {
// Resolve the file beside this module even if Node starts in another directory.
const bytes = await readFile(new URL(file, import.meta.url));
res.writeHead(200, { 'Content-Type': type }).end(bytes);
} catch {
res.writeHead(500).end();
}
}).listen(8765, '127.0.0.1');
Run node server.mjs, open http://127.0.0.1:8765/ and select Load inventory. To inspect the response from another terminal, run:
# In a second terminal, show the headers and print each line as it arrives.
curl --no-buffer -i http://127.0.0.1:8765/sample.ndjson
The sample is small enough to arrive in one chunk. For a real endpoint, use the cURL Command Line Builder to reproduce its request headers. Test through the same reverse proxy and compression settings that visitors use. A proxy may buffer a progressively written response. The --no-buffer flag only affects cURL’s own output.
Force the boundaries that a fast local request can hide
Save these tests as ndjson.test.mjs and run node --test ndjson.test.mjs with Node.js 22.17 or later. The first test feeds the same input twice, first a byte at a time and then all at once. The result should be identical, including the accent in Café and the final null.
import assert from 'node:assert/strict';
import test from 'node:test';
import { readNDJSON, summarize } from './ndjson.mjs';
const encode = text => new TextEncoder().encode(text);
async function parse(chunks, limit) {
const body = new ReadableStream({
start(controller) {
for (const chunk of chunks) controller.enqueue(chunk);
controller.close();
}
});
return Array.fromAsync(readNDJSON(body, limit));
}
test('UTF-8 and CRLF split at every byte', async () => {
const bytes = encode('"Café"\r\n\nnull\n');
// One byte per chunk splits both the accented character and the CRLF pair.
const chunks = Array.from(bytes, byte => Uint8Array.of(byte));
assert.deepEqual(await parse(chunks), ['Café', null]);
assert.deepEqual(await parse([bytes]), ['Café', null]);
});
test('rejects malformed or oversized records', async () => {
await assert.rejects(parse([Uint8Array.of(0xff, 10)]), TypeError);
await assert.rejects(parse([encode('1\n{\n')]), /line 2/);
await assert.rejects(parse([encode('true')]), /Missing newline/);
await assert.rejects(parse([encode('12'), encode('3\n')], 2), /too long/);
});
test('breaking the loop cancels an open source', async () => {
// Leave the source open so the test can observe cancellation after break.
let cancelled = false;
const body = new ReadableStream({
start(controller) { controller.enqueue(encode('1\n2\n')); },
cancel() { cancelled = true; }
});
for await (const record of readNDJSON(body)) {
assert.equal(record, 1);
break;
}
assert.equal(cancelled, true);
});
test('validates inventory fields and adds large quantities exactly', async () => {
const item = { id: '9007199254740993', name: 'Café', quantity: Number.MAX_SAFE_INTEGER };
// A data URL lets fetch read the fixture without starting an HTTP server.
const url = rows => 'data:application/x-ndjson,' + encodeURIComponent(
rows.map(row => JSON.stringify(row) + '\n').join('')
);
assert.deepEqual(await summarize(url([item, item])), { count: 2, units: 18014398509481982n });
await assert.rejects(summarize(url([{ ...item, id: 1 }])), /Invalid item 1/);
});
When you try this on your own export, time the first validated record and the final total separately. The Resource Timing guide explains the network measurements you can compare with those application timings. If the goal is to keep a page updated with events and reconnect after a disconnection, our Server-Sent Events tutorial covers that different delivery model.

