From 990ce73ecf68c41534515c786f299599f07a30c6 Mon Sep 17 00:00:00 2001 From: Tilman Date: Wed, 3 Dec 2025 00:08:09 +0100 Subject: [PATCH] User cancelling download error handling --- routes/api/files/download-directory.tsx | 37 ++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/routes/api/files/download-directory.tsx b/routes/api/files/download-directory.tsx index e3afd70..8411c24 100644 --- a/routes/api/files/download-directory.tsx +++ b/routes/api/files/download-directory.tsx @@ -95,19 +95,48 @@ export const handler: Handlers = { // Convert Node.js stream to Web ReadableStream const readableStream = new ReadableStream({ async start(controller) { + let isCancelled = false; + zipStream.on('data', (chunk: Buffer) => { - controller.enqueue(new Uint8Array(chunk)); + try { + if (!isCancelled) { + controller.enqueue(new Uint8Array(chunk)); + } + } catch (error) { + // Stream already closed/cancelled, ignore + isCancelled = true; + } }); zipStream.on('end', () => { - controller.close(); + try { + if (!isCancelled) { + controller.close(); + } + } catch (error) { + // Stream already closed, ignore + } }); zipStream.on('error', (error: Error) => { - console.error('Zip stream error:', error); - controller.error(error); + if (!isCancelled) { + console.error('Zip stream error:', error); + try { + controller.error(error); + } catch { + // Stream already closed, ignore + } + } }); }, + cancel() { + // Clean up when client cancels the download + try { + zipStream.destroy(); + } catch { + // Ignore cleanup errors + } + }, }); return new Response(readableStream, {