-2

I am very confused on Deno documentation. It has ReadableStream and WritableStream API, but it doesn’t have a documentation to use it.

I want to read from ReadableStream and write to WritableStream, how can I do that in Deno?

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
thebluetropics
  • 82
  • 2
  • 10
  • is [this](https://deno.land/manual/examples/fetch_data#files-and-streamshttps://deno.land/manual/examples/fetch_data#files-and-streams) what you looking for ? – bogdanoff Jul 23 '22 at 02:00

1 Answers1

1

I want to read from ReadableStream and write to WritableStream, how can I do that in Deno?

Here's a basic TypeScript example demonstrating manual use of the readable and writable parts of a TextEncoderStream (which is a subtype of TransformStream) with verbose console logging:

so-73087438.ts:

const decoder = new TextDecoder();
const decode = (chunk: Uint8Array): string =>
  decoder.decode(chunk, { stream: true });

const stream = new TextEncoderStream();

(async () => {
  for await (const chunk of stream.readable) {
    const message = `Chunk read from stream: "${decode(chunk)}"`;
    console.log(message);
  }
  console.log("Stream closed");
})();

const texts = ["hello", "world"];

const writer = stream.writable.getWriter();
const write = async (chunk: string): Promise<void> => {
  await writer.ready;
  await writer.write(chunk);
};

for (const str of texts) {
  const message = `Writing chunk to stream: "${str}"`;
  console.log(message);
  await write(str);
}

console.log("Releasing lock on stream writer");
writer.releaseLock();
console.log("Closing stream");
await stream.writable.close();

% deno --version
deno 1.24.0 (release, x86_64-apple-darwin)
v8 10.4.132.20
typescript 4.7.4

% deno run so-73087438.ts
Writing chunk to stream: "hello"
Chunk read from stream: "hello"
Writing chunk to stream: "world"
Chunk read from stream: "world"
Releasing lock on stream writer
Closing stream
Stream closed


Covering the entirety of the API for WHATWG Streams is out of scope for a Stack Overflow answer. The following links will answer any question you could ask about these streams:

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • I just realized a couple minutes ago that Streams is a Web APIs adapted to Deno, and not a Deno APIs. Maybe this is why I dont found the doc on Deno – thebluetropics Jul 23 '22 at 02:43