ItSolutionStuff.com

How to Delete File If Exists in Node JS?

By Hardik Savani • September 15, 2021
Node JS

This example is focused on node js delete file if exists. if you want to see example of how to delete file if exists in node js then you are a right place. This tutorial will give you simple example of node js remove file if exists. In this article, we will implement a node js delete file sync. Let's see bellow example node js unlinkSync delete file.

We will use fs npm package for remove file in node.js. fs package provide unlinkSync() for remove file. let's see simple example

Step 1: Create Node App

run bellow command and create node app.

mkdir my-app

cd my-app

npm init

Step 2: Create server.js file

Make sure you have "uploads" folder in root directory with some files on that.

server.js

const fs = require('fs');

const filePath = './uploads/image-1616507041795.png';

fs.exists(filePath, function(exists) {

if(exists) {

console.log('File exists. Deleting now ...');

fs.unlinkSync(filePath);

} else {

console.log('File not found, so not deleting.');

}

});

now you can simply run by following command:

node server.js

Output:

i hope it can help you...

Tags: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Download Image from URL in Node JS?

Read Now →

How to Generate QR Code in Node JS?

Read Now →

Node JS Send Email with Attachment Example

Read Now →

How to Send Email using Gmail Account in Node.js?

Read Now →

How to Get Current Date and Time in Node JS?

Read Now →

How to Get Client IP Address in Node JS?

Read Now →

How to Render HTML File in Node JS Express?

Read Now →

How to use Underscore JS in Node JS App?

Read Now →

Node JS Sort Array of Objects by Value Example

Read Now →

How to Create and Use .env File in Node JS?

Read Now →

Axios HTTP requests in Node JS Example

Read Now →