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");
}

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 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 - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course