Skip to content

Instantly share code, notes, and snippets.

@piotrgredowski
Last active April 3, 2019 11:16
Show Gist options
  • Save piotrgredowski/a2f816f9fa927818938fc8dd06061281 to your computer and use it in GitHub Desktop.
Save piotrgredowski/a2f816f9fa927818938fc8dd06061281 to your computer and use it in GitHub Desktop.
const
path = require('path'),
fs = require('fs');
const waitForFileToExist = (filepath, forTime = 5000) => {
return new Promise((resolve, reject) => {
const
filedir = path.dirname(filepath),
filename = path.basename(filepath);
if (fs.existsSync(filepath)) {
resolve(true);
} else {
let watcher;
const timer = setTimeout(() => {
watcher.close();
reject(`${filename} does not exist`)
}, forTime);
watcher = fs.watch(filedir, function (event, who) {
if (event === 'rename' && who === filename) {
if (fs.existsSync(filepath)) {
watcher.close();
clearTimeout(timer);
resolve(true);
} else {
watcher.close();
clearTimeout(timer);
reject(`${filename} does not exist`)
}
}
})
}
})
}
waitForFileToExist('a.txt').then((doesFileExist) => {
console.log(doesFileExist);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment