Edge Developer Platform
  • Edge Functions
    • Overview
    • Getting Started
    • Operation Guide
      • Function Management
      • Web Debugging
      • Function Trigger
      • Environment Variable
      • Code Replica
    • Runtime APIs
      • addEventListener
      • Cache
      • Cookies
      • Encoding
      • Fetch
      • FetchEvent
      • Headers
      • Request
      • Response
      • Streams
        • ReadableStream
        • ReadableStreamBYOBReader
        • ReadableStreamDefaultReader
        • TransformStream
        • WritableStream
        • WritableStreamDefaultWriter
      • Web Crypto
      • Web standards
      • Images
        • ImageProperties
    • Sample Functions
      • Example Overview
      • Obtaining Client URL Information
      • Customization Based on Client Geo Location
      • Obtaining Client Geo Location Information
      • Batch Redirect
      • URL rewrite based on regular expressions
      • Returning an HTML Page
      • Returning a JSON Object
      • Fetch Remote Resources
      • Authenticating a Request Header
      • Modifying a Response Header
      • Performing an A/B Test
      • Setting Cookies
      • Performing Redirect Based on the Request Location
      • Using the Cache API
      • Caching POST Requests
      • Responding in Streaming Mode
      • Merging Resources and Responding in Streaming Mode
      • Protecting Data from Tampering
      • Rewriting a m3u8 File and Configuring Authentication
      • Adaptive Image Resize
      • Image Adaptive WebP
      • Customize Referer restriction rules
      • Remote Authentication
      • HMAC Digital Signature
      • Naming a Downloaded File
      • Obtaining Client IP Address
      • Complex origin-pull URL rewriting
      • Web Bot Auth
    • Practical Tutorial
      • Overview
      • Origin retrieval based on user IP/geographic location
        • EdgeOne Implementation of Session Persistence Based on Client IP Addresses
        • EdgeOne Implementation of Origin-Pull Based on Client's Geo Location
      • APK dynamic packaging
        • EdgeOne enables dynamic packaging of Android APKs.
          • Feature Overview
          • Step 1: Preprocess the Android APK Parent Package
          • Step 2: Write the Channel Information into the APK Package with EdgeOne Edge Functions
      • Canary Release and Region-specific Execution
      • Adaptive Image Format Conversion via Edge Functions
      • Two Ways to Implement CDN Origin-pull Via Edge Function: Fetch and Passthrough
  • KV Storage
    • Overview
    • Operation Guide
  • Edge reasoning
    • Edge Inference Overview
    • Quick Guide

Merging Resources and Responding in Streaming Mode

In this example, three video clips are merged into one video, and the merged video is played on a client based on the order in which the video clips are merged. This example demonstrates how to use an edge function to fetch multiple remote resources, read and merge the resources in streaming mode, and respond to a client request by using the merged resource in streaming mode.

Sample Code

async function sequentialCombine(urls, destination) {
try {
// Process each URL in order
for (let i = 0; i < urls.length; i++) {
const url = urls[i];

// Get the current clip
const response = await fetch(url);

if (!response.ok) {
console.error(`Failed to obtain video clip: ${url}, Error code: ${response.status}`);
continue;
}

// Get a readable stream
const readable = response.body;

// Execute pipeTo immediately to write the current clip to the target stream
try {
await readable.pipeTo(destination, {
preventClose: true // Keep the stream open for subsequent writing
});
} catch (e) {
console.error(`Stream processing errors (${url}): ${e.message}`);
}
}
} catch (err) {
console.error(`Merging video streams error: ${err.message}`);
} finally {
// Close the stream after all fragments are processed
const writer = destination.getWriter();
writer.close();
writer.releaseLock();
}
}

async function handleRequest(request) {
// The URLs of the video clips.
const urls = [
'https://vod.example.com/stream-01.mov',
'https://vod.example.comm/stream-02.mov',
'https://vod.example.com/stream-03.mov',
];

// Creating a Transformation Flow
const { readable, writable } = new TransformStream();

// Get and merge video clips in sequence
sequentialCombine(urls, writable);

// Returns the merged video stream response
return new Response(readable, {
headers: {
'content-type': 'video/mp4',
}
});
}

// Listening for fetch events
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});

Sample Preview

In the address bar of the browser, enter a URL that matches a trigger rule of the edge function to preview the merged video. View the response header and verify that the video is transferred in chunked mode.




References