Nodejs validation file exists, if not, wait for it to exist

I generate the files automatically, and I have another script that will check if the given file is already generated, so how could I implement such a function:

function checkExistsWithTimeout(path, timeout) 

which checks if a path exists, if not, wait for it, use a timeout.

+7
source share
5 answers

fs.watch () API is what you need.

Be sure to read all warnings mentioned there before using it.

0
source share

This is very hack, but works for quick things.

 function wait (ms) { var now = Date.now(); var later = now + ms; while (Date.now() < later) { // wait } } 
0
source share

Here is the solution:

 // Wait for file to exist, checks every 2 seconds function getFile(path, timeout) { const timeout = setInterval(function() { const file = path; const fileExists = fs.existsSync(file); console.log('Checking for: ', file); console.log('Exists: ', fileExists); if (fileExists) { clearInterval(timeout); } }, timeout); }; 
0
source share

You can implement it like this if you have node 6 or higher.

 const fs = require('fs') function checkExistsWithTimeout(path, timeout) { return new Promise((resolve, reject) => { const timeoutTimerId = setTimeout(handleTimeout, timeout) const interval = timeout / 6 let intervalTimerId function handleTimeout() { clearTimeout(timerId) const error = new Error('path check timed out') error.name = 'PATH_CHECK_TIMED_OUT' reject(error) } function handleInterval() { fs.access(path, (err) => { if(err) { intervalTimerId = setTimeout(handleInterval, interval) } else { clearTimeout(timeoutTimerId) resolve(path) } }) } intervalTimerId = setTimeout(handleInterval, interval) }) } 
0
source share

Assuming you plan to use Promises , since you did not specify a callback in your method signature, you can check if the file exists and look at the directory at the same time, and then allow whether the file exists or the file is created before the expiration timeout.

 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(); } }); }); } 
0
source share

All Articles