Open tlover-code opened 3 days ago
A Switch.download()
function wouldn't make sense for the core nx.js runtime, since it would not need to rely on any native APIs. It would be better as an external module.
Can you elaborate on what kind of error/issue you are seeing though?
The code above cannot increase the loading speed beyond 3MB/s because it needs to write to the memory card every 3 seconds to avoid memory overflow. I tried writing every 100MB, but the download speed remained unchanged. However, when using the following code, the download speed reached 8MB/s. I noticed that the code below does not have the step of writing to the memory card.
export async function fetchProgress(
url: string,
{ onProgress, onDownloadStart }: FetchOptions
) {
// Step 1: start the fetch and obtain a reader
const response = await fetch(url);
if (!response.ok) {
throw new Error(response.status.toString());
}
const reader = response.body!.getReader();
// Step 2: get total length
const contentLength = +response.headers.get("Content-Length")!;
// Step 3: read the data
let receivedLength = 0; // received that many bytes at the moment
let last = { time: 0, value: 0 };
let counter = 0;
let speed = 0;
const stream = new ReadableStream({
start(controller) {
onDownloadStart();
return pump();
function pump(): Promise<
ReadableStreamReadResult<Uint8Array> | undefined
> {
return reader.read().then(({ done, value }) => {
// When no more data needs to be consumed, close the stream
if (done) {
controller.close();
return;
}
// Enqueue the next data chunk into our target stream
controller.enqueue(value);
receivedLength += value.length;
const progress = receivedLength / (contentLength / 100) / 100;
const current = { time: Date.now(), value: receivedLength };
if (counter % 50 === 0) {
if (last.time) {
const time = current.time - last.time;
const val = current.value - last.value;
speed = byteToMB(val / (time / 1000));
}
last = { ...current };
}
onProgress({
progress: isFinite(progress) ? progress : 0,
receivedLength,
contentLength,
speed,
});
counter += 1;
return pump();
});
}
},
});
return new Response(stream);
}
I'm having trouble downloading files with JavaScript code; the download speed is only 3 MB/s. I hope you can add the function Switch.download(url, pathStore, bigFile).