mas cm
mas cm

Reputation: 131

specify whether or not a file exists in node.js

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

Upvotes: 1

Views: 4258

Answers (2)

BrunoLM
BrunoLM

Reputation: 100351

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:

Upvotes: 1

mas cm
mas cm

Reputation: 131

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

Upvotes: 0

Related Questions