Wait for the file to finish writing to disk before processing in Node.js

I have a Node function that checks if a file exists, and if it does, the function does some additional processing. My problem is that Node checks if my file exists, but it doesn't wait for the file to finish writing. How can I see if the file exits and wait for the file to finish writing before executing the rest of my function?

var doStuff = function(filename, callback) {


  // writing to file here

  fs.exists(filename, function(exists) {
    if (exists) {
      // do stuff
      callback()
    }
  });

});

      

I see there is a synchronous version fs.exists

. Should I use this? Or do I need to add a call to setTimeout to wait a small amount of time before activating the file? Which option is better?

+3


source to share


1 answer


Just put it in your fs.writeFile

callback. Be sure to check for errors, but may save you a call fs.exists

:



fs.writeFile(filename, "stuff to write", function (err) {

  if (err) {
    // something went wrong, file probably not written.
    return callback(err);
  }

  fs.exists(filename, function(exists) {
    if (exists) {
      // do stuff
      callback()
    }
  });

});

      

+2


source







All Articles