0

I would like to check if a file exists in NodeJS.

I saw this solution in another post :

const tryRequire = (path) => {
  try {
   return require(`${path}`);
  } catch (err) {
   return null;
  }
};

But is it really a good solution?

In my case I'm checking a lot of file, so I'm gonna import with the require each file I'll check (so a lot of files). I just want to know if the file exists or not and don't import it.

How could I do this?


EDIT:

I'm explaining my issue in details.

I'm in a Symfony and React project. I'm new with React.

There is a possibility to upload images in a chat. When uploading an image, I call a Symfony route. In this route I use Liip Imagine bundle. So I'm doing something like this to cache the image :

public function new(Request $request, SerializerInterface $serializer): Response
{
    $rewardImagePath = $this->uploaderHelper->asset($media, 'imageFile');
        if($rewardImagePath) {
            $cacheImagePath = $this->cacheManager->getBrowserPath($rewardImagePath, 'live_feed_message');
        }
}

The issue is that function getBrowserPath give me the URL of the future cached file. But the file takes a significant time (like 5/10 seconds sometimes) to be created. So in my front I have the new chat message but in reality the file associated don't exists on the server. So it displays a message without image.

For some unknow reasons, if I'm doing a while file exists in this controller, I got a time out and the file is never created. That's why I'm trying to check the file existence in react side.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
Alexis
  • 347
  • 5
  • 16

1 Answers1

-1

you can try:

function doesFileExist(urlToFile) {
var xhr = new XMLHttpRequest();
xhr.open('HEAD', urlToFile, false);
xhr.send();

if (xhr.status == "404") {
    return false;
} else {
    return true;
}
}
Aurele Collinet
  • 138
  • 1
  • 16