Streaming NDJSON With Async Iteration
Consume newline-delimited JSON streams line by line using async iteration over the response body, parsing each record with error isolation.
Code
async function* ndjsonLines(body) {
let buffer = '';
const decoder = new TextDecoder();
for await (const chunk of body) {
buffer += decoder.decode(chunk, { stream: true });
let newline;
while ((newline = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, newline).trim();
buffer = buffer.slice(newline + 1);
if (line) yield line;
}
}
buffer += decoder.decode();
if (buffer.trim()) yield buffer.trim();
}
async function ingest(url) {
let processed = 0;
let failed = 0;
const res = await fetch(url, { headers: { Accept: 'application/x-ndjson' } });
if (!res.ok) throw new Error('stream failed: ' + res.status);
for await (const line of ndjsonLines(res.body)) {
try {
const record = JSON.parse(line);
processed += 1;
if (processed % 1000 === 0) console.log('processed', processed);
} catch {
failed += 1; // 单行损坏不影响整条流
}
}
return { processed, failed };
}
const stats = await ingest('https://api.example.com/events/stream');
console.log('ingest done:', stats);How the snippet works
Streaming NDJSON With Async Iteration comes down to the function ingest.
for await (const chunk of body) and while ((newline = buffer.indexOf('\n')) !== -1) nest, one inside the other. Await points sequence the asynchronous work; a rejection lands at the awaiting line. Failure is loud: Error aborts the current operation instead of degrading it.
The result comes back as an object carrying processed.
What to watch for
- Uses
fetch, so it needs a browser context — it will not run as-is in Node without shims. - The guard
!res.okshort-circuits the flow with an earlythrowwhen its condition holds.
Applying it
The main signature reads async function ingest(url)
The demo output is labeled (processed, ingest done:), so every printed line maps back to its originating operation.
The call returns processed.
Statements that matter
const res = await fetch(url, { headers: { Accept: 'application/x-ndjson' } });
const stats = await ingest('https://api.example.com/events/stream');
if (!res.ok) throw new Error('stream failed: ' + res.status);
Interactive Tools for This Topic
FAQ
- Does `ingest` modify its input?
- It does not. Inputs are only read; the return value is freshly built.
- Is there a failure path for bad input?
- The code throws `Error` — the guard `!res.ok` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. The file defines `ingest` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.