Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs check file exists, if not, wait till it exist

Tags:

I'm generating files automatically, and I have another script which will check if a given file is already generated, so how could I implement such a function:

function checkExistsWithTimeout(path, timeout) 

which will check if a path exists, if not, wait for it, util timeout.

like image 754
wong2 Avatar asked Oct 02 '14 16:10

wong2


1 Answers

Assuming you're planning on using Promises since you did not supply a callback in your method signature, you could check if the file exists and watch the directory at the same time, then resolve if the file exists, or the file is created before the timeout occurs.

function checkExistsWithTimeout(filePath, timeout) {     return new Promise(function (resolve, reject) {          var timer = setTimeout(function () {             watcher.close();             reject(new Error('File did not exists and was not created during the timeout.'));         }, timeout);          fs.access(filePath, fs.constants.R_OK, function (err) {             if (!err) {                 clearTimeout(timer);                 watcher.close();                 resolve();             }         });          var dir = path.dirname(filePath);         var basename = path.basename(filePath);         var watcher = fs.watch(dir, function (eventType, filename) {             if (eventType === 'rename' && filename === basename) {                 clearTimeout(timer);                 watcher.close();                 resolve();             }         });     }); } 
like image 69
Jake Holzinger Avatar answered Sep 29 '22 10:09

Jake Holzinger