Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

I have a Node function that checks to see if a file exists, then if it does exist, the function does some further processing. My problem is that Node is checking if my file exists, but it's not waiting for the file to finish being written to. How can I see if a file exits and wait for the file to finish being written too before executing the remainder of my function?

var doStuff = function(filename, callback) {


  // writing to file here

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

});

I see that there is a synchronous version of fs.exists. Should I use that? Or should I add a setTimeout call to wait a small amount of time before actin on the file? What option is best?

like image 963
turtle Avatar asked Aug 20 '14 23:08

turtle


1 Answers

Just throw it into your fs.writeFile callback. Be sure to check for errors though, might save you the trouble of calling 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()
    }
  });

});
like image 186
SamT Avatar answered Nov 08 '22 21:11

SamT