Trending

World technology news

→
An NDJSON record containing İzmir. The C4 and B0 bytes of İ span two chunks, and byte 0A ends the line.
Software Engineering · 2026
Software Engineering

Read NDJSON streams in Node.js without breaking UTF-8 characters

Parse streamed NDJSON across UTF-8 byte boundaries, cap each line before decoding, and verify the parser with reproducible tests.

Developer's JournalPublished: Nov 28, 20266 min read
Reading progress0%
In this article
  1. Define the contract around physical lines
  2. Split bytes before decoding UTF-8
  3. Apply a byte limit to the accumulating line
  4. Consume each record through the async generator
  5. Move the chunk boundary through the fixture
  6. Decide what happens after a partial write

Define the contract around physical lines

A warehouse service exports transfer records as one JSON value per physical line. The consumer processes records as they arrive. A read can stop halfway through a line or halfway through the UTF-8 bytes for the dotted capital İ in İzmir. The sender defines the record boundaries. Network and file buffering determine the chunk boundaries. In this example, LF is the delimiter and a CR immediately before it is accepted for Windows exports. An empty input yields zero records. A nonempty line at the end of the stream is accepted without LF. One final LF terminates the last record. An additional empty physical line is an error. Embedded newlines inside JSON strings use escape sequences. Pretty-printed JSON spanning multiple physical lines needs a different input contract.

Split bytes before decoding UTF-8

In UTF-8, a continuation byte cannot have the value used by LF. The parser therefore searches for byte 0x0A in incoming data. Once it finds the delimiter, it joins the retained fragments and gives the completed line to TextDecoder. The fatal option rejects malformed encoding that would otherwise be replaced by a substitution character. The ignoreBOM option preserves a leading byte-order mark as a character, allowing JSON.parse to reject it. Some legacy exports use a BOM at the start of a file. Accepting a single file-level BOM would be an explicit compatibility choice. Decoding every chunk independently can corrupt a character when its bytes span two chunks. Decoding the joined line lets the decoder receive every byte of that character together.

Service architectureConceptual sketch · summary of the article's technical flow

Apply a byte limit to the accumulating line

The default limit is 65,536 bytes per physical line. It excludes LF and includes any trailing CR. Checking the limit before copying enforces the same budget for every language. Each retained fragment is copied so a short suffix does not keep the entire backing buffer alive across later reads. The generator can still retain the chunk it is actively walking while the consumer handles a yielded value. It also needs memory for the joined buffer, decoded text, parsed value and the fragments’ object overhead. The byte limit bounds accumulated line data. Source buffering, the size of individual input chunks and consumer queues need their own limits. Rejecting overlong input before reading the delimiter also handles files with a missing line break.

export async function* ndjson(source, maxLineBytes = 65_536) {
  if (!Number.isSafeInteger(maxLineBytes) || maxLineBytes < 1) {
    throw new RangeError('maxLineBytes must be a positive integer');
  }
  const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
  let pieces = [];
  let size = 0;
  let line = 1;

  function append(bytes) {
    if (size + bytes.length > maxLineBytes) {
      throw new RangeError('line ' + line + ': byte limit exceeded');
    }
    if (bytes.length) {
      pieces.push(Buffer.from(bytes));
      size += bytes.length;
    }
  }

  function readLine() {
    let bytes = Buffer.concat(pieces, size);
    if (bytes.at(-1) === 13) bytes = bytes.subarray(0, -1);
    if (!bytes.length) throw new Error('line ' + line + ': empty record');
    try {
      return JSON.parse(decoder.decode(bytes));
    } catch (cause) {
      throw new Error('line ' + line + ': invalid UTF-8 or JSON', { cause });
    }
  }

  for await (const chunk of source) {
    if (!(chunk instanceof Uint8Array)) throw new TypeError('expected byte chunks');
    const bytes = Buffer.isBuffer(chunk) ? chunk :
      Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
    let start = 0;
    for (let end = bytes.indexOf(10); end !== -1; end = bytes.indexOf(10, start)) {
      append(bytes.subarray(start, end));
      const record = readLine();
      pieces = [];
      size = 0;
      line += 1;
      start = end + 1;
      yield record;
    }
    append(bytes.subarray(start));
  }
  if (size > 0) yield readLine();
}

Consume each record through the async generator

The reader accepts a Node.js Readable or another async iterable of byte chunks. Each yield hands a completed JSON value to the consumer. If the consumer awaits a write inside its loop, it will request the next value after that write finishes. The producer can still buffer according to its own configuration. JSON.parse accepts JSON scalars and arrays as well as objects. Warehouse-specific rules belong in a validation step that checks properties such as transfer ID, quantity and location. That makes an invalid business record distinguishable from broken syntax or encoding. Returning early from a loop can close a Readable. If an application needs to reuse a stream after an early exit, it should choose ownership and closure behavior in its input adapter.

Move the chunk boundary through the fixture

The fixture includes İzmir, a numeric field and a four-byte emoji. It combines CRLF, LF and a final record without a terminator. It splits the same buffer at every possible offset and expects the same three objects each time. Another run passes single-byte chunks to exercise records spanning more than two pieces. Separate cases reject malformed UTF-8, invalid JSON, a blank line and an oversized record. A CRLF case exercises the rule that counts CR in the size limit. A BOM case documents the choice to reject it. These checks verify the expected output of the fixture on the tested Node.js release. A small capture from the real producer provides another way to detect changes in encoding and record delimiters. The 46-byte fixture has 47 split points, including an empty chunk at either end. For small, valid samples you can compare the result with a reference implementation that decodes the entire file. Test equivalent lines with and without CR at the size boundary. Only the line with the extra byte should fail at that limit.

import assert from 'node:assert/strict';
import {Readable} from 'node:stream';
import {ndjson} from './ndjson.mjs';
const collect = async (source, limit) => Array.fromAsync(ndjson(Readable.from(source), limit));
const payload = Buffer.from('{"city":"İzmir"}\r\n{"count":2}\n{"icon":"🧰"}');
for (let split = 0; split <= payload.length; split++) {
  const chunks = [payload.subarray(0, split), payload.subarray(split)];
  assert.deepEqual(await collect(chunks), [{city:'İzmir'}, {count:2}, {icon:'🧰'}]);
}
assert.deepEqual(await collect(Array.from(payload, b => Buffer.from([b]))), [{city:'İzmir'}, {count:2}, {icon:'🧰'}]);
assert.deepEqual(await collect([Buffer.from('1\n')]), [1]);
assert.deepEqual(await collect([]), []);
await assert.rejects(collect([Buffer.from('1\n\n')]), /line 2: empty/);
await assert.rejects(collect([Buffer.from('1\n{x}\n')]), /line 2: invalid/);
await assert.rejects(collect([Buffer.from([34, 0xc4, 34, 10])]), /line 1: invalid/);
await assert.rejects(collect([Buffer.from('123'), Buffer.from('45')], 4), /line 1: byte limit/);
await assert.rejects(collect([Buffer.from('1234\r\n')], 4), /line 1: byte limit/);
await assert.rejects(collect([Buffer.from('\uFEFF1\n')]), /line 1: invalid/);
await assert.rejects(collect(['1\n']), /expected byte/);
console.log(JSON.stringify({byteLength:payload.length, splitPoints:payload.length+1, oneByteChunks:true, repeatedCases:10, node:process.version}));

Decide what happens after a partial write

If line 150 is malformed, the consumer may already have received and written 149 values. Throwing from the iterator does not reverse those writes. An all-or-nothing feed can store rows under a temporary import ID and publish the batch after validation. A row-by-row feed can use an idempotency key made of the source ID and record ID so replaying a file does not duplicate accepted rows. Log the input identity, accepted count and failing line number. Raw rows can contain private data and are generally unnecessary to locate the failure. Distinguish line limits from syntax failures so the producer can tell an oversized record from a truncated export. The retry decision depends on the consumer’s commit policy.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

Which bottleneck would you expect as this solution scales?

No comments yet. Be the first to contribute.

Write a comment

Comments are real visitor contributions. Repeated, link-heavy or abusive submissions may be limited.