I am building an image compressor (with node,react) where after serving the compressed image by res.download()
I want to delete the file for saving space. But if I put await unlink(path)
after res.download(path)
download fails in the client side and show errors in the server. How can I achieve successful deletion without failing to send the file to the client?
My code in the backend:
app.get('/download/:imageName', async (req,res)=>{
let imageName = req.params.imageName
let path = 'uploads/'+imageName;
const compressedImage = await imagemin([path], {
destination: "compressed",
plugins: [
imageminPngquant({
quality: [0.6, 0.8]
}),
imageminMozjpeg(),
imageminGifsicle({lossy: 70}),
imageminSvgo({
plugins: extendDefaultPlugins([
{name: 'removeViewBox', active: false}
])
})
]
});
await res.download(process.cwd()+"/"+compressedImage[0].destinationPath)
let compressedPath = 'compressed/'+path
await unlink(compressedPath,(err)=>{
if(err) throw err;
console.log(compressedPath+ " hase been deleted")
})
})
Thanks