Skip to content

sortJsonl

Eugene Lazutkin edited this page Jun 26, 2026 · 1 revision

sortJsonl

Sort a text JSONL stream (newline-delimited JSON): parse each line to an object, sort with sort, and re-emit JSONL text. A thin convenience over sort + stream-chain's line framing — stream-sorting is otherwise object-mode in / object-mode out, so this is the one text-aware entry point.

import sortJsonl from 'stream-sorting/utils/sort-jsonl.js';

for await (const line of sortJsonl(input, {compare: (a, b) => a.id - b.id, tmpDir: '/var/sort'})) {
  process.stdout.write(line); // each `line` is one JSON object + "\n"
}

input is a text stream — AsyncIterable<string | Uint8Array> | Iterable<…> (a Node Readable in text mode, a generator of chunks, an array of strings, …); chunk boundaries need not align to lines (stream-chain's fixUtf8Stream + lines handle that). The result is an AsyncIterable<string>, one newline-terminated JSON line per item — so concatenating the output is valid JSONL.

Options

Accepts all of sort's options (compare / lessFn, tmpDir / createWrapper, batchSize, stable, onProgress, keepTempFiles) plus:

Option Type Default Description
parse (line) => item JSON.parse Parse one JSONL line into an item.
stringify (item) => string JSON.stringify Serialize one item into a line (no trailing newline).

When to use it — and when not to

sortJsonl is a convenience: it is the stream-chain composition (parse JSONL → sort → stringify) wrapped under a name. If you already have a stream-chain pipeline, compose directly instead — JSONL framing is stream-chain's job, and sort is object-mode in / object-mode out:

import chain from 'stream-chain';
import sort from 'stream-sorting/sort.js';
// chain([textInput, jsonlParse(), …]) → objects → sort(…) → stringify → text

Reach for sortJsonl when text-JSONL in / text-JSONL out is the whole job; reach for the explicit composition when sorting is one stage of a larger pipeline.

See also

sort, polyphaseSort.

Clone this wiki locally