0

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.

4
  • 1
    What do you mean " is not asynchronous and will not work"? Why will it not work? Commented Mar 24, 2018 at 8:24
  • well it does not work when I run it in nodejs to be honest I dont know what "asynchronous " means so that really makes my problem difficult Commented Mar 24, 2018 at 8:36
  • when I run my first code it does not find any file in that directory however the directory should be correct. Ive been struggling to how to make this work for quite some time now. Commented Mar 24, 2018 at 8:41
  • Synchronous code works perfectly well in Node.js, generally we use asynchronous calls for any i/o. This is generally too ensure the efficient use of resources rather than anything else. Commented Mar 24, 2018 at 8:45

2 Answers 2

1

You can do this synchronously with no problem, it might just take awile. If the fs.exists function is not finding a file I'd just ensure your path is exactly correct. I added an extra '/' after /flags as I'm assuming the array of country names does not include this.

const fs = require('fs');
const path = require('path');
const imageDir = '/var/scraper/public/images/flags/';

var filesExist = arr.map((imgObj) => {
  const imgfile = imgObj.country;
  let filePath = path.join(imageDir, imgfile + ".png");
  console.log('Checking existance of file: ', filePath);
  // Return an object with 'exists' property and also the file path
  // To just return the path:
  // return fs.existsSync(filePath) ? filePath: path.join(imageDir, "noimg.png")};
  return { exists: fs.existsSync(filePath), path: fs.existsSync(filePath) ? filePath: path.join(imageDir, "noimg.png")};
});

console.log('Files exist: ', filesExist);
Sign up to request clarification or add additional context in comments.

22 Comments

Hi thanks for your reply . this code looks quite promising. my knowledge with this i quite low imo. If you look in my post #1 how would I make your code loop trough my array to check each and every instance?
Hey @Frederik84, the answer I posted will loop through the arr array. This is what arr.map does. It calls fs.existsSync for each entry in the array. array.map, array.reduce are very powerful!
We're here to help! Good luck with your testing. Node.js can be a little tricky to learn but it's a great technology!
No problemo!! Node is great :)
I'll update the answer, you just want the path, is that right?
|
1

The simplest and lease time consuming solution to this problem would be to simply use fs.existsSync You can find docs for that method here. In fact, if you take a look at fs.exists in the docs you'll notice that fs.exists has been deprecated at least since the last v8 LTS release (this might be why you are having trouble with it).

If you are using a recent version of node with support for it, this is a great opportunity to leverage async/await. It might look something like this:

const fs = require('fs');
const { promisify } = require('util');
const existsAsync = promisify(fs.exists);

async function checkFiles (arr) {
  const arrayLength = arr.length;

  for (let i = 0; I < arrayLength; I++) {
    const countryName = arr[i].country;

    const filePath = `/var/scraper/public/images/flags${countryName}.png`; 
    const fileExists = await fs.existsAsync(filePath);

    console.log(`File flags${contryName}.png exists: ${fileExists}`);
  }
}

8 Comments

"has been deprecated at least since the last v8 LTS release (this might be why you are having trouble with it)." - yes that and synchronous/asynchronous calls got my head spinning , lol Thanks for your answer Ill try to test it right away
also as a small side questio: what is the difference betwen const and var ?
const defines a variable that will not change. It's useful when using the require statement for example.
but for some reason im not able to get this code work I get this error code: " Unexpected token ( -bash: syntax error near unexpected token `(' " error starts here; async function (arr) { , Im sure its me that have done something wrong
Ultimately const creates an immutable binding to the assigned value thus preventing the ability to mutate it. On the other hand, let is very similar to var except that let is constrained to block scope while var is constrained to an entire function regardless of with no regard to block scope. Here is a much better explanation on the topic.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.