Skip to main content

Function Signature

function encodeLines(input: unknown, options?: EncodeOptions): Iterable<string>
Encodes a JavaScript value into TOON format as a sequence of lines. This function yields TOON lines one at a time without building the full string, making it suitable for streaming large outputs to files, HTTP responses, or process stdout.

Parameters

input
unknown
required
Any JavaScript value to encode (objects, arrays, primitives). The value will be normalized to JSON-compatible types.
options
EncodeOptions
Optional encoding configuration.
indent
number
default:"2"
Number of spaces per indentation level.
delimiter
Delimiter
default:"DELIMITERS.comma"
Delimiter to use for tabular array rows and inline primitive arrays.
keyFolding
'off' | 'safe'
default:"'off'"
Enable key folding to collapse single-key wrapper chains. When set to 'safe', nested objects with single keys are collapsed into dotted paths (e.g., data.metadata.items instead of nested indentation).
flattenDepth
number
default:"Infinity"
Maximum number of segments to fold when keyFolding is enabled. Controls how deep the folding can go in single-key chains. Values 0 or 1 have no practical effect (treated as effectively disabled).
replacer
EncodeReplacer
A function to transform or filter values during encoding. Called for the root value and every nested property/element. Return undefined to omit properties/elements (root cannot be omitted).
type EncodeReplacer = (
  key: string,
  value: JsonValue,
  path: readonly (string | number)[]
) => unknown

Returns

result
Iterable<string>
Iterable of TOON lines (without trailing newlines). Each line is a complete TOON line ready to be written or printed.

Behavior

  • Lines are yielded one at a time without building the full string in memory
  • Each line does NOT include a trailing newline character
  • Empty objects yield zero lines
  • Lines do not have trailing whitespace
  • The iterable can be consumed with for-of loops, Array.from(), or spread syntax

Examples

import { encodeLines } from 'toon';

const data = { name: 'Alice', age: 30 };

for (const line of encodeLines(data)) {
  console.log(line);
}
// Output:
// name: Alice
// age: 30

Use Cases

Memory Efficiency

For large data structures, encodeLines avoids building the entire TOON string in memory:
import { encodeLines } from 'toon';

const largeDataset = {
  records: Array.from({ length: 1000000 }, (_, i) => ({ id: i }))
};

// Stream directly to output without holding everything in memory
for (const line of encodeLines(largeDataset)) {
  process.stdout.write(line + '\n');
}

HTTP Streaming

import { encodeLines } from 'toon';

app.get('/data.toon', (req, res) => {
  res.setHeader('Content-Type', 'text/plain');
  
  const data = fetchLargeDataset();
  
  for (const line of encodeLines(data)) {
    res.write(line + '\n');
  }
  
  res.end();
});

Build docs developers (and LLMs) love