The fs.existsSync() method is used to synchronously check if a file already exists in the given path or not. It returns a boolean value which indicates the presence of a file.
Syntax:
fs.existsSync( path )
Parameters: This method accepts a single parameter as mentioned above and described below:
- path: It holds the path of the file that has to be checked. It can be a String, Buffer or URL.
Return Value: It returns a boolean value i.e true if the file exists otherwise returns false.
Below programs illustrate the fs.existsSync() method in Node.js:
Example 1:
const fs = require('fs');
getCurrentFilenames();
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
fileExists = fs.existsSync('world.txt');
console.log("world.txt exists:", fileExists);
function getCurrentFilenames() {
console.log("\nCurrent filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
console.log("\n");
}
|
Output:
Current filenames:
hello.txt
index.js
package.json
hello.txt exists: true
world.txt exists: false
Example 2:
const fs = require('fs');
getCurrentFilenames();
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
if (!fileExists) {
console.log("Creating the file")
fs.writeFileSync("hello.txt", "Hello World");
}
getCurrentFilenames();
fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);
function getCurrentFilenames() {
console.log("\nCurrent filenames:");
fs.readdirSync(__dirname).forEach(file => {
console.log(file);
});
console.log("\n");
}
|
Output:
Current filenames:
hello.txt
index.js
package.json
hello.txt exists: true
Current filenames:
hello.txt
index.js
package.json
hello.txt exists: true
Reference: https://nodejs.org/api/fs.html#fs_fs_existssync_path
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Oct, 2021
Like Article
Save Article