How to Delete All Files in Folder in Node js

The fs.unlink() and rimraf library remove all files or multiple from a folder in node js.

How to Delete All Files from a Folder or Directory in Node js

Here are two methods:

Method 1: Using the built-in fs module

First, you need to install the fs module which comes with Node.js. So open cmd or terminal and run the following command into it:

npm install fs

To delete all files in a folder or directory using Node.js, you can use the following code:

const fs = require('fs');
const path = require('path');
const directoryPath = './your_directory_path_here'; // Replace with your directory path
function deleteFilesInDirectory(directoryPath) {
  fs.readdir(directoryPath, (err, files) => {
    if (err) {
      console.error(`Error reading directory: ${err}`);
      return;
    }
    files.forEach((file) => {
      const filePath = path.join(directoryPath, file);
      fs.unlink(filePath, (err) => {
        if (err) {
          console.error(`Error deleting file ${filePath}: ${err}`);
        } else {
          console.log(`Deleted file: ${filePath}`);
        }
      });
    });
  });
}
deleteFilesInDirectory(directoryPath);

Method 2: Using the rimraf package

To use rimraf package to delete all files from a directory. So, open cmd or terminal and run the following command into it to install it first:

npm install rimraf

To delete all files from a folder in Node.js, here is an example code for that:

const rimraf = require('rimraf');

const directoryPath = './your_directory_path_here'; // Replace with your directory path

rimraf(directoryPath, (err) => {
  if (err) {
    console.error(`Error deleting directory: ${err}`);
  } else {
    console.log(`Deleted directory: ${directoryPath}`);
  }
});

Conclusion

That’s it, you have learned how to delete all files from a directory or folder in Node.js using the Node.js fs module and the rimraf package.

Recommended Tutorials

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *