How to Delete File If Exists in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Download Image from URL in Node JS?
- How to Generate QR Code in Node JS?
- Node JS Send Email with Attachment Example
- How to Send Email using Gmail Account in Node.js?
- How to Get Current Date and Time in Node JS?
- How to Get Client IP Address in Node JS?
- How to Render HTML File in Node JS Express?
- How to use Underscore JS in Node JS App?
- Node JS Sort Array of Objects by Value Example
- How to Create and Use .env File in Node JS?
- Axios HTTP requests in Node JS Example