How to check the file/path exists in Nodejs?

This is a simple tutorial on how to check if a file exists in a file system using nodejs code.

We can use a variety of methods to see if a file exists in Nodes.

  • Using existsSync and exits
  • fs access and accessSync
  • Async and await promises

File checking can be done Synchronously and asynchronous. You can check other posts on How to always run some code when a promise is resolved or rejected, npm command deprecate option is deprecated

fs exists function

fs provides two functions to check the file path that exists in an OS file system. exists: This is an asynchronous way of checking existsSync: Synchronous way of checking file exists or not

Here is an existsSync example

const fs = require("fs");
console.log("start");

if (fs.existsSync("user.xml")) {
  console.log("exists");
}
console.log("completed");

Output:

start
exists
completed

Here is an existing example of a path exists or not

const fs = require("fs");
 console.log('start');

if (fs.exists("user.xml"(err) => {
    if(err)
  console.log("not exists");
});
 console.log('completed');

Check file or folder exists using fs access and accessSync functions

access and accessSync functions are provided to check the file system with reading and write permissions access function for synchronous execution, accessSync for asynchronous operation

fs.constants.F_OK check file is visible or not fs.constants.R_OK and fs.constants.W_OK are for read and write permissions.

Here is an accessSync example

const fs = require("fs");

if (fs.accessSync("user.xml", fs.constants.F_OK)) {
  console.log("exists");
}
console.log("completed");

Here is an access function example

const fs = require("fs");

fs.access("user.xml", fs.constants.F_OK, (err) => {
  if (err) {
    console.log("file not exists", err);
  }
  console.log("file exists");
});

Using Async and Await with promises

We can also check using async and await for asynchronous execution.

Here is a sequence of steps

  • isFileExists method, a new promise is created and resolved to an existing file, else resolved to an error in case of errors.
function ISIL exists(path){
  return new Promise((resolve, fail) => fs.access(path, fs.constants.F_OK,
    (err, data) => err ? fail(err) : resolve(data))

}

async function checkFile() {
  var exists = await isFileExists('user.xml');
  if(exists){
    console.log('file exists');
  }
}

Conclusion

To Sum up, We learned different ways of checking path that exists in Nodejs using the fs module.