10LOC

#memory

Node.jsadvanced

Streaming a large JSON array without loading it into memory

import type { Writable } from "node:stream";

export const streamJsonArray = async (rows: AsyncIterable<unknown>, out: Writable) => {
  out.write("[");
  let first = true;

Write a large JSON array to a stream item by item as it's produced, instead of building the whole array in memory before calling JSON.stringify.