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:
f
This is very much a hack, but works for quick stuff.
function wait (ms) {
var now = Date.now();
var later = now + ms;
while (Date.now() < later) {
// wait
}
}
function verifyFileDownload(extension) {
browser.sleep(150000); //waiting for file to download
const fs = require('fs');
let os = require('os');
var flag = true;
console.log(os.userInfo());
fs.readdir('/Users/' + require("os").userInfo().username + '/Downloads/', (error, file) => {
if (error) {
throw error;
}
console.log('File name' + file);
for (var i = 0; i < file.length; i++) {
const fileParts = file[i].split('.');
const ext = fileParts[fileParts.length - 1];
if (ext === extension) {
flag = false;
}
}
if (!flag) {
return;
}
throw error;
});
};
function holdBeforeFileExists(filePath, timeout) {
timeout = timeout < 1000 ? 1000 : timeout;
return new Promise((resolve)=>{
var timer = setTimeout(function () {
resolve();
},timeout);
var inter = setInterval(function () {
if(fs.existsSync(filePath) && fs.lstatSync(filePath).isFile()){
clearInterval(inter);
clearTimeout(timer);
resolve();
}
}, 100);
});
}
fs.watch() API is what you need.
Be sure to read all the caveats mentioned there before you use it.
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();
}
});
});
}
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);
};