I currently have a piece of code that downloads a file onto the local filesystem. It's fairly straightforward:
var downloadFile = function(request, file_name, cb) {
var final_path = file_name + '.pdf';
var file = fs.createWriteStream(final_path);
// Save temporary file to disk
var save_file = request.pipe(file);
save_file.on('finish', function () {
cb('success', final_path);
});
}
However, on occasion, I would encounter an error (later on in the code) that suggests that the file had not been fully downloaded. When I open the file manually myself, it appears fine. Additionally, the bug seems to happen more frequently when we have a fairly large amount of users simultaneously on the site.
All of this clearly suggests to me a possible race condition, but I'm not exactly sure where or how this could be happening. My understanding of node is that it's single threaded with non-blocking I/O, which would suggest any possible culprits be in the I/O parts: the createWriteStream and subsequent pipe (possibly the 'finish' callback handler). Perhaps they are being overwritten somehow or called out-of-order. But how? The finish handler seems like a standard promise/callback. Any insights would be greatly appreciated!
-Edward