<!DOCTYPE html>
How to remove all files from directory without removing directory in Node js
When working with Node.js, you may come across a situation where you need to remove all files from a directory without actually removing the directory itself. This can be done easily using the built-in fs module in Node.js.
Here is a step-by-step guide on how to achieve this:
- First, require the fs module in your Node.js application:
- Next, use the fs.readdir method to read all the files in the directory:
- Then, loop through all the files and use the fs.unlink method to remove each file:
- Finally, you can console log a message to indicate that all the files have been removed:
- Don’t forget to handle any errors that may occur during the process:
const fs = require('fs');
fs.readdir(directoryPath, (err, files) => {
files.forEach(file => {
fs.unlink(`${directoryPath}/${file}`, err => {
if (err) throw err;
});
});
console.log('All files have been removed from the directory.');
if (err) throw err;
And that’s it! You have successfully removed all files from a directory without removing the directory itself in Node.js.
Happy coding!