Files and data

Keep incomplete records between stream chunks

Treat stream chunks as arbitrary pieces of data, not complete records. Keep an unfinished tail between chunks and process only records whose delimiter has actually arrived.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const chunks = ['{"id":', '1}\n{"id":2', '}\n'];
let pending = "";
const records = [];
for (const chunk of chunks) {
  pending += chunk;
  let end;
  while ((end = pending.indexOf("\n")) !== -1) {
    records.push(JSON.parse(pending.slice(0, end)));
    pending = pending.slice(end + 1);
  }
}
if (pending) records.push(JSON.parse(pending));
console.log(records.map(row => row.id).join(","));

How it works

The pending string carries a partial JSON line into the next iteration. Complete lines are removed only after parsing. This isolates framing from chunk delivery: one chunk can contain half a record or several records.

Limits and mistakes

Real byte streams also require a streaming text decoder to handle split UTF-8 sequences. Impose a maximum record length so a missing delimiter cannot grow pending without bound. Add explicit malformed-record handling for production imports.

Check the result

Expect 1,2. Split the same input at every possible character boundary and confirm the reconstructed records remain the same.

Sources

Reference documentation for the behavior used in this guide: