Home  Nodejs   The web str ...

The Web Streams API example

Here's a basic example demonstrating the usage of the Web Streams API (ReadableStream and WritableStream) in a web browser context. Web Streams are particularly useful for handling large amounts of data asynchronously and efficiently. In this example, we'll create a simple text stream to illustrate how data can be processed and piped from a readable stream to a writable stream.

Example: Using Web Streams API

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Web Streams Example</title>
</head>
<body>
  <div>
    <h2>Web Streams Example</h2>
    <button id="startBtn">Start Streaming</button>
    <p id="output"></p>
  </div>

  <script>
    // Function to create a readable stream with sample data
    function createStream() {
      const data = ['Hello', 'world', 'from', 'web', 'streams!'];
      const readableStream = new ReadableStream({
        start(controller) {
          data.forEach(value => controller.enqueue(value + '\n'));
          controller.close();
        }
      });
      return readableStream;
    }

    // Function to consume the readable stream and display data
    async function consumeStream() {
      const readable = createStream();
      const writable = new WritableStream({
        write(chunk) {
          outputElement.textContent += chunk;
        }
      });
      
      // Piping the readable stream to the writable stream
      await readable.pipeTo(writable);
    }

    // Event listener to start streaming when button is clicked
    const startBtn = document.getElementById('startBtn');
    const outputElement = document.getElementById('output');
    startBtn.addEventListener('click', () => {
      consumeStream();
    });
  </script>
</body>
</html>

Explanation:

  1. HTML Structure:

    • The HTML file includes a button (Start Streaming) and a <div> to display the output of the streamed data.
  2. JavaScript (Web Streams API):

    • createStream Function:

      • Creates a ReadableStream that generates sample data (Hello\n, world\n, etc.).
      • Uses a controller to enqueue each string and then closes the stream.
    • consumeStream Function:

      • Creates instances of ReadableStream and WritableStream.
      • The WritableStream writes each chunk of data (chunk) to the outputElement.
      • Uses the pipeTo method to pipe the data from the readable stream to the writable stream.
    • Event Listener:

      • Listens for a click on the Start Streaming button and triggers the consumeStream function.

How It Works:

Published on: Jun 18, 2024, 01:51 PM  
 

Comments

Add your comment