How to check if the file exists or not in Node.js
In this post we will give you information about How to check if the file exists or not in Node.js. Hear we will give you detail about How to check if the file exists or not in Node.jsAnd how to use it also give you demo for it if it is necessary.
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 pathif (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 pathfs.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 pathtry { fs.accessSync(path, fs.constants.R_OK); console.log("File is found");}catch (err) { console.log("File is not found");}Hope this code and post will helped you for implement How to check if the file exists or not in Node.js. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs
