I want to return a generated file with koa (2) and after the client finished receiving the file, the file should be deleted.
// this function is called by Koa
async myMethod (ctx) {
const file = await something()// generate a file
ctx.attachment(path.basename(file))
ctx.body = fs.createReadStream(file)
// how can I await here for the client to fully receive file?
await fs.promises.unlink(file)
}
I could do this:
ctx.body.on('end', async () => {
console.log('client finished receiving')
await fs.promises.unlink(file)
})
but I would rather put the delete logic in a separate middleware, and therefore I have to wait for the file to be fully sent before returning from the function