Express response.download() Not Behaving as Expected
I'm using following code to track active download counts.
router.get('/download/:fileName', (req, res) => {
let fileName = req.params.fileName;
let baseFilePath='/home/filePath';
incrementDownloadCount(fileName);
return res.download(
`${baseFilePath}/${fileName}`,
`${fileName}`,
function (err) {
if (err) {
console.log(`ERROR ++ : ${err}`);
} else {
console.log('download completed');
}
decrementDownloadCount(fileName);
}
);
});
When each time download started it increments download count by one, but after few seconds 'download completed' is printed to the log and download count get decremented while the downloading is in progress.
As of the nodejs express documentation the callback function is called after the download is finished or in an event of exception. Can anyone please help on this ?
I'm using nodejs 14.16.0 and express 4.17.1
Hi @bamunusingha I'm sorry you are having trouble. Unfortunately to help diagnose your issue we need to be able to reproduce it. Are you seeing this on your local environment or only when you deploy it out? If only when deployed, do you have any kind of reverse proxy in front of Express that would be completing the transfer earlier than the end client does? Any and all information you have about your exact set up will help us to determine what is going on.
FWIW, the callback is called when Node.js raises the event finish (https://nodejs.org/dist/latest-v15.x/docs/api/http.html#http_event_finish) as that is the last event Node.js provides regarding the transfer of the data for a response, so it's possible this may end up needing to be escalated to Node.js, but if you can provide full details for how to reproduce, we can help determine that.
Hi, This happen in the production environment. Im using cloudflare for DNS and nginx as a reversed proxy in the server side.
Hi @bamunusingha unfortunately the callback will not do what you want with NGINX between your node.js server and the client, as Node.js can only tell when the file was transferred to NGINX, not when the client got it.
Hi,
Thanks for the help.
Finally this issue is fixed when I disable nginx proxy cache by setting
proxy_request_buffering off;
proxy_max_temp_file_size 0;
inside the location / block