Is there any way to know when server has streamed all data to the client?

39 Views Asked by At

I'm using Hono with Deno to serve uploaded files to other users. When a certain amount of download reached the file should be deleted from server to save disk space. The important note is I must delete it just after the server has sent the last bit of data to the last user. Our concern is just about the server has send it whether the user has got it or not. This was some code I tried,

app.get('/download/:key/:userId/:fileId', async (ctx) => {
  try{

    // previous code gets file data from database [eg: originalName]

    ctx.newResponse(file.readable, {
      headers: new Headers({
        'Content-Type': 'application/octet-stream',
        'Content-Disposition': `attachment; filename="${originalName}"`,
      }),
    });
    
    console.log('File served');
    
    //if download is > 10, delete the file
    if (downloadCount && Number(downloadCount + 1) >= maxDownload){

        await redis.del(`chat:${key}:file:${fileId}`);
        await Deno.remove(`./uploads/${key}/${fileId}`);

        console.log('File deleted');
        //if './uploads/key' is empty, delete the directory
        Deno.stat(`./uploads/${key}`)
            .then(async (dir) => {
                if (dir.isDirectory && dir.size === 0){
                    await Deno.remove(`./uploads/${key}`);
                    console.log('Directory deleted');
                }
            }
        ).catch(() => {});
    }
  } catch (_){
      console.log(_);
  }
});

We get to the console.log('File served'); line because the response stream is being sent asynchronously. That's all I know about Hono.

My goal is to be able to detect when the server has done its work, then do the further actions.

Searched Deno, Hono repo, Stactkverflow. But did not found any relevant thing.

0

There are 0 best solutions below