jimmywarting / StreamSaver.js

StreamSaver writes stream to the filesystem directly asynchronous
https://jimmywarting.github.io/StreamSaver.js/example.html
MIT License
3.97k stars 413 forks source link

Just a little help :)) #283

Closed numairawan closed 2 years ago

numairawan commented 2 years ago

Hi , you gave me the example code to download chunks and save it as one file.

const chunks = [
    'https://example.com/',
    'https://example.com/',
]

function concatenateRequests(requests) {
    const ts = new TransformStream()
    const pump = () => {
        const it = requests.next()
        if (it.done) return ts.writable.close();
        fetch(it.value).then(res => {
            console.log(res.body);
            return res.body.pipeTo(ts.writable, { preventClose: true })
        }).then(pump, ts.writable.abort.bind(ts.writable));
    }

    pump();

    return ts.readable;
  }

  concatenateRequests(chunks.values()).pipeTo(streamSaver.createWritableStream('archive.zip'))

But i cant catch the error and retry for new url that i will get from server. So can you please make it i loop? for example

async function test(chunks) {

    const ts = new TransformStream();

    for (let x = 0; x < chunks.length; x++) {

        await fetch(x)
            .then(async res => {

                if (!res.ok || res.status !== 200) {
                    // get error message from body or default to response status
                    return Promise.reject(error);
                    throw ('Download failed');
                }

                return res.body.pipeTo(ts.writable, {
                    preventClose: true
                })
            })
            .then(ts.writable.abort.bind(ts.writable))
            .catch(async (error) => {

                // renew the url
                var newURL = await get_fresh_link(x);
                urls[x] = newURL;

                if (x == 1) {
                    x = 1;
                } else {
                    x = x - 1;
                }

            });

    }

    return ts.readable;

}

test(chunks).pipeTo(streamSaver.createWritableStream('archive.zip'))

But its not working.

jimmywarting commented 2 years ago

if you are downloading a zip from a server then i really recommend you to use the server if at all possible first and formost

can't stretch how important this is... it have better support in all browsers, browsers can pause, resume and also retry failed attempts and continue from where it left of if you also provide a Accept-Ranges: bytes header along with a content-length

streamsaver and other alike is mostly just for client side generated content.