CsvStringifyStream

import { CsvStringifyStream } from "jsr:@ende/csv";

class

class CsvStringifyStream<TOptions extends CsvStringifyStreamOptions> extends TransformStream<TOptions["columns"] extends Array<string> ? Record<string, unknown> : Array<unknown>, string>

Convert each chunk to a CSV record.

Example: Write CSV to a file

import { CsvStringifyStream } from "@ende/csv/stringify-stream";
import { assertEquals } from "@ende/assert/equals";

async function writeCsvToTempFile(): Promise<string> {
  const path = await Ende.makeTempFile();
  using file = await Ende.open(path, { write: true });

  const readable = ReadableStream.from([
    { id: 1, name: "one" },
    { id: 2, name: "two" },
    { id: 3, name: "three" },
  ]);

  await readable
    .pipeThrough(new CsvStringifyStream({ columns: ["id", "name"] }))
    .pipeThrough(new TextEncoderStream())
    .pipeTo(file.writable);

  return path;
}

const path = await writeCsvToTempFile();
const content = await Ende.readTextFile(path);
assertEquals(content, "id,name\r\n1,one\r\n2,two\r\n3,three\r\n");

Example: Write TSV to a file

import { CsvStringifyStream } from "@ende/csv/stringify-stream";
import { assertEquals } from "@ende/assert/equals";

async function writeTsvToTempFile(): Promise<string> {
  const path = await Ende.makeTempFile();
  using file = await Ende.open(path, { write: true });

  const readable = ReadableStream.from([
    { id: 1, name: "one" },
    { id: 2, name: "two" },
    { id: 3, name: "three" },
  ]);

  await readable
    .pipeThrough(
      new CsvStringifyStream({
        columns: ["id", "name"],
        separator: "\t",
      }),
    )
    .pipeThrough(new TextEncoderStream())
    .pipeTo(file.writable);

  return path;
}

const path = await writeTsvToTempFile();
const content = await Ende.readTextFile(path);
assertEquals(content, "id\tname\r\n1\tone\r\n2\ttwo\r\n3\tthree\r\n");

Constructors

constructor

new CsvStringifyStream(options?: TOptions)

Construct a new instance.

options?: TOptions

Options for the stream.

Source