简体   繁体   中英

NodeJS race condition?

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

Try this:

var downloadFile = function(request, file_name, cb) {
  var final_path = file_name + '.pdf';
  var file = fs.createWriteStream(final_path);

  // Save temporary file to disk
  request.pipe(file);

  request.on('end', function () {
    cb('success', final_path);
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM