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?
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()
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With