Stream line-by-line JSON (NDJSON)
Handle each record as soon as it arrives, without waiting for the whole response.
AJAX · Stream line-by-line JSON (NDJSON)Advanced
async function* readNDJSON(url) {
const res = await fetch(url);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // last piece may be incomplete
for (const line of lines) if (line.trim()) yield JSON.parse(line);
}
if (buffer.trim()) yield JSON.parse(buffer);
}
(async () => { for await (const row of readNDJSON('/api/export.ndjson')) console.log(row); })();ndjsonstreamlineslarge data