by Sai gowtham

How to check if the file exists or not in Node.js

In this tutorial, we are going to learn about how to check if a file exists or not using the Node.js fs (file system) module.

The fs.existsSync() method

We can use the fs.existsSync() method to check if a file exists in the file system.

The fs.existsSync() method returns true if a given path exists else it returns false.

Here is an example:

const fs = require("fs");

const path = "./app.js"; // file path

if (fs.existsSync(path)) {
    console.log("File is found");
} else {
    console.log("File is not found");
}

In the above example, we have passed the path variable as an argument to fs.existsSync() method, so that it logs file is found if the following file path exists else it logs File is not found.

Note: The fs.existsSync() method checks the file synchronously so that it blocks the execution context until it finishes the process.

The fs.access() method

To check if a file exists asynchronously without opening it, we can use the fs.access() method.

const fs = require("fs");

const path = "./app.js"; // file path

fs.access(path, (error) => {
    if (error) {
        console.log("File is not found");
    } else {
        console.log("File is found");
    }
})

In the above code, we have passed the callback function as a second argument to the fs.access() method, so that it is invoked with an error argument once a file checking process is completed.

The fs.accessSync() method

The fs.accessSync() method is also used to check the file existence synchronously but without opening it.

const fs = require("fs");

const path = "./app.js"; // file path

try {
    fs.accessSync(path, fs.constants.R_OK);
    console.log("File is found");
}
catch (err) {
    console.log("File is not found");
}

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course