Search code examples
javascriptdenowhatwg-streams-api

How to use streams in Deno?


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?


Solution

  • 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: