Streaming import: chunk boundaries and line framing
Project milestone
Assemble complete records from arbitrary byte chunks. UTF-8 decoding and newline framing are separate stages, so neither chunk boundaries nor split CRLF sequences create false records.
Run the examples
In projects/stream-import/, save the snippet as example.cjs and run node example.cjs in a fresh process.
const {importRows,chunks}=require('./import.cjs');(async()=>console.log(JSON.stringify(await importRows(chunks(['PEN\t','2\r','\nBOOK\t3'])))))();Expected console output:
[{"sku":"PEN","quantity":2},{"sku":"BOOK","quantity":3}]Framing joins split chunks and flush emits the last row.
In projects/stream-import/, save the snippet as example.cjs and run node example.cjs in a fresh process.
const {importRows,chunks}=require('./import.cjs');(async()=>console.log((await importRows(chunks([]))).length))();Expected console output:
0No bytes means no rows.
Implementation and contract
Import bytes through TextDecoderStream with fatal decoding, then through splitLines(). The transform retains unfinished text until a newline arrives, strips a trailing carriage return, and emits the final nonempty pending line at flush. It rejects long lines. Read import.cjs and follow the pipeline from chunks() to the writable sink.
Common mistakes
Do not assume one read equals one record. A missing final newline does not imply that the last complete field should be discarded.
Acceptance task
Split the same two rows at several different byte positions and verify identical results.
Project source, setup and tests: projects/stream-import/README.md. Read the implementation before modifying it; the tests check the supplied baseline, not every possible implementation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Streaming import: chunk boundaries and line framing — Knowledge Check
Assess implementation decisions and project behavior.
What does splitLines retain between chunks?
Which stage handles incomplete UTF-8 sequences?
Why implement flush?
In the Streaming import: chunk boundaries and line framing lab, what does this independent example log? const {importRows,chunks}=require('./import.cjs'); (async()=>console.log(JSON.stringify(await importRows(chunks(['PEN\t','2\r','\nBOOK\t3'])))))();
In the Streaming import: chunk boundaries and line framing lab, what does this independent example log? const {importRows,chunks}=require('./import.cjs'); (async()=>console.log((await importRows(chunks([]))).length))();