JsonStringifyStream

import { JsonStringifyStream } from "jsr:@ende/json";

class

class JsonStringifyStream extends TransformStream<unknown, string>

Convert each chunk to JSON string.

This can be used to stringify JSON lines, NDJSON, JSON Text Sequences, and Concatenated JSON.

You can optionally specify a prefix and suffix for each chunk. The default prefix is "" and the default suffix is "\n".

Example: Basic usage

import { JsonStringifyStream } from "@ende/json/stringify-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([{ foo: "bar" }, { baz: 100 }])
  .pipeThrough(new JsonStringifyStream());

assertEquals(await Array.fromAsync(stream), [
  `{"foo":"bar"}\n`,
  `{"baz":100}\n`
]);

Example: Stringify stream of JSON text sequences

Set options.prefix to \x1E to stringify JSON Text Sequences.

import { JsonStringifyStream } from "@ende/json/stringify-stream";
import { assertEquals } from "@ende/assert";

const stream = ReadableStream.from([{ foo: "bar" }, { baz: 100 }])
  .pipeThrough(new JsonStringifyStream({ prefix: "\x1E", suffix: "\n" }));

assertEquals(await Array.fromAsync(stream), [
  `\x1E{"foo":"bar"}\n`,
  `\x1E{"baz":100}\n`
]);

Example: Stringify JSON lines from a server

import { JsonStringifyStream } from "@ende/json/stringify-stream";

// A server that streams one line of JSON every second
Ende.serve(() => {
  let intervalId: number | undefined;
  const readable = new ReadableStream({
    start(controller) {
      // Enqueue data once per second
      intervalId = setInterval(() => {
        controller.enqueue({ now: new Date() });
      }, 1000);
    },
    cancel() {
      clearInterval(intervalId);
    },
  });

  const body = readable
    .pipeThrough(new JsonStringifyStream()) // Convert data to JSON lines
    .pipeThrough(new TextEncoderStream()); // Convert a string to a Uint8Array

  return new Response(body);
});

Constructors

constructor

new JsonStringifyStream(options?: StringifyStreamOptions)

Constructs new instance.

options?: StringifyStreamOptions

Options for the stream.

Source