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:
-
HTML Structure:
- The HTML file includes a button (
Start Streaming
) and a<div>
to display the output of the streamed data.
- The HTML file includes a button (
-
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.
- Creates a
-
consumeStream
Function:- Creates instances of
ReadableStream
andWritableStream
. - The
WritableStream
writes each chunk of data (chunk
) to theoutputElement
. - Uses the
pipeTo
method to pipe the data from the readable stream to the writable stream.
- Creates instances of
-
Event Listener:
- Listens for a click on the
Start Streaming
button and triggers theconsumeStream
function.
- Listens for a click on the
-
How It Works:
- When the
Start Streaming
button is clicked, theconsumeStream
function is called. createStream
generates sample data as a readable stream.- The
WritableStream
listens for incoming data (chunk
) from the readable stream and appends it to theoutputElement
. - Each chunk of data (
Hello\n
,world\n
, etc.) is displayed in sequence in the<p id="output">
element as it is streamed from theReadableStream
to theWritableStream
.
Published on: Jun 18, 2024, 01:51 PM