Node.js – How to check if Directory or File exists

  • by
node-js-check-if-a-directory-folder-file-exists-fs-existsSync-example

In this tutorial we will learn How to check if a Directory or a File exists using Node.js. The built-in fs module in Node.js helps in working with file system. It provides different functions to create, rename, delete, edit files, directory and folder.

fs.existSync() function checks if a provided file or a folder exists or not.

Check if a File exists using fs.existsSync():

The checkExists(pathToCheck) will check the file exists or not using fs.existsSync() function and log a output. In this code we are checking for 2 files with name wallpaper1.png and wallpaper2.png inside folder: media>images

The folder structure is given after the code example for the reference.

const fs = require("fs");

let file1 = './media/images/wallpaper1.png';
let file2 = './media/images/wallpaper2.png';

CheckExists(file1);
CheckExists(file2);

function CheckExists(pathToCheck) {
if (fs.existsSync(pathToCheck))
console.log(pathToCheck + " exists");
else
console.log(pathToCheck + " do not exists");
}

My file structure in this project:

node-js-project-directory-structure

Output:

PS C:\Code\Node\fileSystem> node fs-exists.js
./media/images/wallpaper1.png exists
./media/images/wallpaper2.png do not exists
PS C:\Code\Node\fileSystem>

DOWNLOAD SOURCE CODE

Check if a Directory/Folder exists using fs.existSync():

The below code will check if the folders images and videos exists inside the media folder.

const fs = require("fs");

let images = './media/images';
let videos = './media/videos';

CheckExists(images);
CheckExists(videos);

function CheckExists(pathToCheck) {
if (fs.existsSync(pathToCheck))
console.log(pathToCheck + " exists");
else
console.log(pathToCheck + " do not exists");
}

Output:

PS C:\Code\Node\fileSystem> node fs-exists.js
./media/images exists
./media/videos do not exists
PS C:\Code\Node\fileSystem>

Code Snapshot:

node-js-check-if-a-directory-folder-file-exists-fs-existsSync-example

DOWNLOAD SOURCE CODE

We have also made a tutorial on:

How to rename a file in Node.js

Renaming a folder or a directory in Node.js

How to create directory using Node.js

Node.js – Create, read and write text files.

HTTP module in Node.js

Install Node.js on Windows.

Node.js – How to create PDF documents.