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.