How To Check If File Or Folder Exists In NodeJS – Simple Examples

Welcome to a quick tutorial on how to check if a file or folder exists in NodeJS. Need to do a quick check on a certain file or folder?

We can use the exist, stat, or access functions in the file system module to check if a file/folder exists in NodeJS.

  • const fs = require("fs");
  • if (fs.existsSync(TARGET)) { EXISTS } else { NO }
  • try { fs.statSync(TARGET); EXISTS } catch (err) { NO }
  • try { fs.accessSync(TARGET); EXISTS } catch (err) { NO }

That covers the quick basics, but read on for better examples!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes File Folder Check Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

FILE FOLDER CHECK

All right, let us now get into the examples of how to check if a file or folder exists in NodeJS.

 

1) EXIST

1-exist.js
// (A) FS MODULE + TARGET FOLDER/PATH
const fs = require("fs"),
      target = "./README.txt";

// (B) EXISTS SYNC - VALID
if (fs.existsSync(target)) {
  console.log(target + " exists");
} else {
  console.log(target + " does not exist");
}

// (C) EXISTS ASYNC - DEPRECATED
fs.exists(target, (result) => {
  if (result) { console.log(target + " exists"); }
  else { console.log(target + " does not exist"); }
});

The exists() function is probably one of the most common examples you will find on the Internet, but take note:

  • existsSync() returns a boolean true/false, and it is still valid at the time of writing.
  • But interestingly, exists() has been deprecated for whatever reason… The official documentation now recommends the use of stat() or access() instead.

 

2) STAT

2-stat.js
// (A) FS MODULE + TARGET FOLDER/PATH
const fs = require("fs"),
      target = "./README.txt";

// (B) STAT SYNC
try {
  var stats = fs.statSync(target);
  console.log(stats); // EXISTS - STATS
} catch (err) {
  console.log(err); // NOT EXISTS OR CANNOT ACCESS
}

// (C) STAT ASYNC
fs.stat(target, (err, stats) => {
  // NOT EXISTS OR CANNOT ACCESS
  if (err) { console.log(err);  }
  // EXISTS - STATS
  else { console.log(stats); }
});

This should be pretty self-explanatory, stat() returns an object with the file/folder statistics on success, throws an error if it is unable to access the target.

 

 

3) ACCESS

3-access.js
// (A) FS MODULE + TARGET FOLDER/PATH
const fs = require("fs"),
      target = "./README.txt";

// (B) ACCESS SYNC
try {
  // EXISTS - ACCESSSYNC RETURNS "UNDEFINED"
  var test = fs.accessSync(target);
  console.log(target + " exists");
} catch (err) {
  // NOT EXIST - ACCESSSYNC THROWS AN ERROR
  console.log(target + " does not exists");
}

// (C) ACCESS ASYNC
// F_OK - VISIBLE (EXISTS)
// R_OK - CAN READ
// W_OK - CAN WRITE
// X_OK - CAN EXECUTE
fs.access(target, fs.F_OK, (err) => {
  // NOT EXIST, DOES NOT HAVE ACCESS
  if (err) { console.log(err); }
  // OK - EXIST
  else { console.log(target + " exists"); }
});

This is one that threw me off a little.

  • The original intention of access() is to check if a file/folder exists, or if we have read/write/execute permissions.
  • Take note that it returns undefined on a successful check, not a boolean true.
  • Yes, it throws an error if unable to access the file/folder instead.

 

 

4) DO NOT USE ACCESS & READ/WRITE TOGETHER

4a-not-good.js
// DON'T DO THIS!
const fs = require("fs"),
      target = "./dummy.txt";

fs.access(target, (err) => {
  if (err) { console.log(err); }
  else {
    fs.open(target, "wx", (err, fd)) {
      // WRITE FILE
    }
  }
});

Lastly, this is a warning from the official documentation itself – Don’t use access() and open() together… It will result in a “read/write race” between these functions and can potentially mess the file up.

4b-good.js
// DO THIS!
const fs = require("fs"),
      target = "./dummy.txt";

fs.open(target, "wx", (err, fd) => {
  if (err) { console.log(err); }
  else {
    // WRITE FILE
  }
});

Just open() the file directly and catch any errors instead.

 

 

USEFUL BITS & LINKS

That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.

 

INFOGRAPHIC CHEAT SHEET

Check File Folder Exists In NodeJS (Click To Enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *