In Node.js, you may need to delete all files from a directory for various reasons, such as cleaning up temporary files, preparing for the storage of new files, or as part of a maintenance task. Deleting files from a directory involves using the Node.js fs
module and rimraf
package to interact with the file system.
In this tutorial, you will learn a step-by-step guide on when and how to delete all files from a directory or folder in Node.js.
How to Delete All Files from a Folder/Directory in Node js
Here are two methods for deleting all files in a folder/directory using node js:
- Method 1: Using the built-in
fs
module - Method 2: Using the
rimraf
package
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
And also you can use rimraf package to delete all files from a directory. So, open cmd or terminal and run the following command into it:
npm install rimraf
Using rimraf package, you can 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.