
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 exists
- fs access and accessSync
- Async and await promises
File checking can be done Synchronous and asynchronous.
fs exists function
fs
provides two functions to check file path exists in a 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 exists example for 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 file system with read 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 are sequence of steps
- isFileExists method, new promise is created and resolved to an existed file,else resolved to an error incase of errors.
function isFileExists(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 exists in Nodejs using fs module.