specify whether or not a file exists in node.js

3.9k views Asked by At

i use this code to specify whether or not a file exists:

if(fs.exists('../../upload/images/book/2.jpg')){
    console.log("yes the file exist");
} else{
        console.log("there is no file");
      }  

While the file is there, it always says it does not exist(there is no file) i use fs.stat(...) too , but again it gives the result (there is no file)

Folder structure:

root_app  
--------|.tmp  
--------|api  
------------|controllers  
------------------------|BookContoller.js (My code run from here)
--------|...(And the rest of the folders)  
--------|upload  
---------------|images  
----------------------|book  
---------------------------|2.jpg

thank you

2

There are 2 answers

1
mas cm On

My problem was solved.
Apparently, we should use fs.accessSync() OR fs.access() instead of fs.exists()
Check out this link

This procedure can also be performed:

function Custom_existsSync(filename) {
  try {
    fs.accessSync(filename);
    return true;
  } catch(ex) {
    return false;
  }  

if(Custom_existsSync(filename)){
    ....
}  

Thanks to everyone who helped me

4
BrunoLM On

fs.exists is asynchronous. To make your code work you could just change it to fs.existsSync.

Also you have the wrong path to your file, you need to use path.resolve or __dirname, so the script will know where to find the file.

if(fs.existsSync(path.resolve('../../upload/images/book/2.jpg'))) {

See documentation: