Trending

World technology news

→
An event stream writes a temporary file under backpressure. A final rename makes the completed NDJSON available.
Software Engineering · 2026
Software Engineering

Stream an NDJSON export in Node.js and publish the completed file

Write events one line at a time with the Node.js pipeline. Publish the completed file in a final rename and test that an interrupted export preserves the existing output.

Developer's JournalPublished: Nov 28, 20266 min read
Reading progress0%
In this article
  1. Start with one export that can grow
  2. Follow the writer's rate of progress
  3. Publish the file after the stream finishes
  4. Test both paths with small fixtures
  5. Use a database source with a clear consistency rule
  6. Report the boundary the consumer can trust

Start with one export that can grow

An administration page exports a day of events to NDJSON. Its first implementation collects the records in an array, serializes them, and writes the combined string. On a quiet day the code is straightforward and the result is easy to inspect. A busy day is different. The record objects and their serialized form can stay in memory at the same time. Concurrent exports compete with the regular requests handled by the same process. A streaming implementation can produce one JSON value at a time and let the file writer determine how fast it moves. The output remains a file that another application can read line by line. Pay attention to the largest record as well as the number of records. A source that reads in advance can also increase memory before the writer ever sees a line. This example runs on Node.js 24 and gives the job an explicit point at which the completed file becomes visible.

Follow the writer's rate of progress

A Node.js writable stream signals when its queue reaches a threshold. Code that calls write directly must wait for drain when write returns false. It must also handle a write that ends early or fails. Here, pipeline connects the source, async generator, and file stream and propagates failures through the chain. The generator produces a string for each incoming record. When the destination slows down, the stream machinery limits further pulls as its buffers fill. The highWaterMark setting is a buffering threshold for a stream. Memory also depends on what the source has already fetched and the size of the objects in flight. One enormous record can still take substantial memory at the moment it is serialized. Measure the largest line, the source page size, and the number of concurrent jobs alongside resident memory. Those figures help distinguish upstream work from pressure at the file output.

Service architectureConceptual sketch · summary of the article's technical flow
Technical referencesNode.js Streams ↗

Publish the file after the stream finishes

The sample creates a unique temporary directory under the destination's parent directory. Inside it, the file writer opens events.ndjson with the exclusive wx flag. The transform serializes every record with JSON.stringify and appends one line feed. A newline within a string is escaped as part of JSON, so a consumer can split the file at physical line boundaries and parse each value individually. An undefined top-level value or a circular object causes the job to reject. The pipeline waits for the write to finish, and the flush option asks Node to flush the file descriptor before closing it. The rename call then moves the completed output to the destination. The temporary location and destination share a parent filesystem. If the source fails midway, cleanup removes the scratch file, and an existing export keeps its contents. The example assumes each job has its own destination name.

import { createWriteStream } from 'node:fs';
import { mkdtemp, rename, rmdir, unlink } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { pipeline } from 'node:stream/promises';

export async function exportRows(rows, destination) {
  const scratch = await mkdtemp(join(dirname(destination), '.export-'));
  const partial = join(scratch, 'events.ndjson');
  try {
    const file = createWriteStream(partial, { flags: 'wx', flush: true });
    await pipeline(rows, async function* (source) {
      for await (const row of source) {
        const line = JSON.stringify(row);
        if (line === undefined) throw new Error('Record is not a JSON value');
        yield line + '\n';
      }
    }, file);
    await rename(partial, destination);
  } finally {
    await unlink(partial).catch(error => {
      if (error.code !== 'ENOENT') throw error;
    });
    await rmdir(scratch);
  }
}

Test both paths with small fixtures

Use three records to test a normal export. Include an accented character, a quotation mark, and a literal newline inside a value. Once the job resolves, read the target as UTF-8, split nonempty lines, parse them, and compare the result with the original records. The last line ends with a line feed. Next, use a generator that yields once and throws. Check the destination after the error and compare it with the file that existed before the attempt. Run the same case with a fresh destination name. A failed export should leave that name absent. Inspect the parent directory for a leftover scratch directory after both runs. A larger streaming benchmark can then repeat one record many times using a generator. Keep concurrent jobs and destination disk capacity in view when comparing runs. The small fixture validates what readers will observe when the export succeeds or fails.

Use a database source with a clear consistency rule

An export can request one page at a time from a database. With a stable unique event ID, carry the last seen ID forward and ask for greater values in the same order. Yield each page's records before requesting the next page. Setting the page size puts an explicit bound on how many ordinary records a driver fetches together. Decide which moment the file represents. For an append-only table with increasing IDs, an upper ID captured at the start can exclude later inserts. A table that permits updates to existing records requires a different consistency mechanism if every row must represent the same instant. Options include a suitable database snapshot or immutable source versions. Record which interval and consistency rule applied. That information helps someone reconcile the export with a later report, especially when new events arrive while the job is running.

Report the boundary the consumer can trust

A queued export can mark itself complete after both pipeline and rename have resolved. Record rows and bytes written and the last source ID when it exists. Those measurements make repeatability and discrepancies easier to understand. Give concurrent jobs distinct destination names or coordinate ownership of a shared destination outside this function. Test errors on the target platform, including permissions and a consumer that may hold the current file open. A temporary file and a final rename provide a clear handoff for ordinary process failures. Full crash durability depends on what the filesystem guarantees for directory metadata as well as the file content. A system with that requirement needs a platform-specific design and test. For everyday throughput work, start by measuring how far ahead a source reads with a slow consumer and by proving a failed export leaves the existing artifact readable.

Be the first reader ✎ Write a comment

Reader discussion

Discussion prompt

What would you change first for maintainability and testing in your own project?

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.