Im trying to check the file system on my server to check if a file exists or not. This simple problem became actually quite a challenging task. Here is my basic code which does not work:
var fs = require('fs');
var arrayLength = arr.length;
for (var i = 0; i < arrayLength; i++) {
var imgfile = arr[i].country
fs.exists('/var/scraper/public/images/flags' + imgfile + ".png", (exists) => {
console.log(exists ? 'it\'s there' : 'not here!');
});
}
Its come to my attention that this is not asynchronous and will not work. I found this link: https://nodejs.org/dist/latest-v9.x/docs/api/fs.html#fs_fs_exists_path_callback
and my code should be built like this.
fs.open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === 'EEXIST') {
console.error('myfile already exists');
return;
}
throw err;
}
writeMyData(fd);
});
I was hoping to get some help to help me rewrite my code to make it asynchronous?
any help at all with this would be much appreciated.