The Wayback Machine - https://web.archive.org/web/20240606163546/https://www.geeksforgeeks.org/node-js-fs-existssync-method/
Open In App

Node fs.existsSync() Method

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Example 1: Below programs illustrate the fs.existsSync() method in Node.js:

Javascript




// Node.js program to demonstrate the
// fs.existsSync() method
 
// Import the filesystem module
const fs = require('fs');
 
// Get the current filenames
// in the directory
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 to get current filenames
// in directory
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: Below programs illustrate the fs.existsSync() method in Node.js

// Node.js program to demonstrate the 
// fs.existsSync() method

// Import the filesystem module
const fs = require('fs');

// Get the current filenames
// in the directory
getCurrentFilenames();

// Check if the file exists
let fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);

// If the file does not exist
// create it
if (!fileExists) {
console.log("Creating the file")
fs.writeFileSync("hello.txt", "Hello World");
}

// Get the current filenames
// in the directory
getCurrentFilenames();

// Check if the file exists again
fileExists = fs.existsSync('hello.txt');
console.log("hello.txt exists:", fileExists);

// Function to get current filenames
// in directory
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

We have a Cheat Sheet on Nodejs fs modules where we covered all the fs methods to check those please go through Node File System Module Complete Reference this article.



Previous Article
Next Article

Similar Reads

Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
There are many different ways to install node.js on a computer. The simplest method to verify whether node.js has been properly installed in your computer is simply type node-v in the command prompt or Windows PowerShell. But many times, it happens, most commonly if you're a beginner, the command prompt prints the output something like this: 'node'
2 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 <= n. Examples: Input : list: 1->3->4->5 n = 4, x = 2 Output : 1->2->3->4->5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10->8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
Node.js Http2ServerRequest.method Method
The Http2ServerRequest.method is an inbuilt application programming interface of class Http2ServerRequest within the http2 module which is used to get the string representation of the request method. Syntax: const request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the string represe
3 min read
Node.js http.IncomingMessage.method Method
The http.IncomingMessage.method is an inbuilt application programming interface of class Incoming Message within the inbuilt http module which is used to get the type of request method as a string. Syntax: request.method Parameters: This method does not accept any argument as a parameter. Return Value: This method returns the request type name as a
2 min read
Node.js URLSearchParams.has() Method
In URLSearchParams interface, the has() method returns a Boolean which tells us that if the parameter with input name exists it will return true, else false. Syntax: var Bool = URLSearchParams.has(name) Returns: True - if name present, else it will return False. Parameters: name - Input the name of the parameter. Example1: let url = new URL('https:
1 min read
Node.js hmac.update() Method
The hmac.update() method is an inbuilt method of class HMAC within the crypto module which is used to update the data of hmac object. Syntax: hmac.update(data[, inputEncoding])Parameters: This method takes the following two parameters: data: It can be of string, Buffer, TypedArray, or DataView type. It is the data that is passed to this function.in
2 min read