Last updated: Apr 5, 2024
Reading timeยท4 min
To delete all files in a directory using Node.js:
fs.readdir()
method to get the names of the files in the directory.fs.unlink()
method to delete each file.Promise.all()
method to await the Promises returned from the
fs.unlink()
method.import fs from 'fs/promises'; import path from 'path'; // ๐๏ธ if you use CommonJS require() // const fs = require('fs/promises'); // const path = require('path'); async function deleteAllFilesInDir(dirPath) { try { const files = await fs.readdir(dirPath); const deleteFilePromises = files.map(file => fs.unlink(path.join(dirPath, file)), ); await Promise.all(deleteFilePromises); } catch (err) { console.log(err); } } deleteAllFilesInDir('./my-directory').then(() => { console.log('Removed all files from the specified directory'); });
The code sample above uses the ES6 modules import/export syntax.
If you use the CommonJS require()
syntax, use the following import statements
instead.
const fs = require('fs/promises'); const path = require('path');
The example assumes that your project has the following folder structure.
my-project/ โโโ my-directory/ โโโ a.txt โโโ b.txt โโโ c.txt โโโ index.js
The deleteAllFilesInDir
function takes a directory path as a parameter and
deletes all files in the specified directory.
Notice that we imported the fs
module from fs/promises
to be able to use
async/await.
import fs from 'fs/promises'; import path from 'path'; async function deleteAllFilesInDir(dirPath) { try { const files = await fs.readdir(dirPath); const deleteFilePromises = files.map(file => fs.unlink(path.join(dirPath, file)), ); await Promise.all(deleteFilePromises); } catch (err) { console.log(err); } } deleteAllFilesInDir('./my-directory').then(() => { console.log('Removed all files from the specified directory'); });
The fsPromises.readDir method takes a path and returns a promise that fulfills with an array of the names of the files in the specified directory.
const files = await fs.readdir(dirPath);
We used the Array.map() method to get an array of the unresolved Promises from the fsPromises.unlink() method.
const deleteFilePromises = files.map(file => fs.unlink(path.join(dirPath, file)), );
The fsPromises.unlink()
method takes a path and returns a Promise that
fulfills with undefined
upon success.
The method deletes the file at the specified path asynchronously.
The last step is to use the Promise.all() method to wait for all Promises in the array to resolve.
await Promise.all(deleteFilePromises);
Once the Promises are resolved, all files in the directory are deleted.
If you want to delete the files and the subdirectories in the specified directory, use the following approach instead.
import fs from 'fs/promises'; // ๐๏ธ if you use CommonJS require() // const fs = require('fs/promises'); async function deleteAllInDir(dirPath) { try { await fs.rm(dirPath, {recursive: true}); await fs.mkdir(dirPath); } catch (err) { console.log(err); } } deleteAllInDir('./my-directory').then(() => { console.log('Removed all files from the specified directory'); });
The code sample deletes the entire directory and then recreates it.
This is equivalent to deleting all files and subdirectories in the specified path, assuming you haven't changed the directory's permissions.
You can also delete all files in a directory synchronously.
import fs from 'fs'; import path from 'path'; // ๐๏ธ if you use CommonJS require() // const fs = require('fs'); // const path = require('path'); function deleteAllFilesInDir(dirPath) { try { fs.readdirSync(dirPath).forEach(file => { fs.rmSync(path.join(dirPath, file)); }); } catch (error) { console.log(error); } } deleteAllFilesInDir('./my-directory'); console.log('Removed all files from the specified directory');
Notice that we imported fs
from fs
and not from fs/promises
this time.
If you use the CommonJS require()
syntax, use the following import statement
instead.
const fs = require('fs'); const path = require('path');
We used the fs.readdirSync() method to get an array of the file names in the directory and then used the Array.forEach() method to iterate over the array.
On each iteration, we use the fs.rmSync() method to remove each file.
The method synchronously removes files and directories and returns undefined
.
We could've also used the fs.unlinkSync() method to achieve the same result.
import fs from 'fs'; import path from 'path'; // ๐๏ธ if you use CommonJS require() // const fs = require('fs'); // const path = require('path'); function deleteAllFilesInDir(dirPath) { try { fs.readdirSync(dirPath).forEach(file => { fs.unlinkSync(path.join(dirPath, file)); }); } catch (error) { console.log(error); } } deleteAllFilesInDir('./my-directory'); console.log('Removed all files from the specified directory');
You can also use the popular fs-extra package to delete all files in a directory.
Generate a package.json
file in the root directory of your project by running
the following command.
npm init -y
Use the following command to install the fs-extra
package.
# with NPM npm install fs-extra # or with YARN yarn add fs-extra
Import and use the package to delete all files in the given directory.
import fsExtra from 'fs-extra'; // ๐๏ธ if you use CommonJS require() // const fsExtra = require('fs-extra'); try { fsExtra.emptyDirSync('./my-directory'); console.log('All files in the directory deleted successfully'); } catch (err) { console.log(err); }
The fsExtra.emptyDirSync()
method takes a path and empties the specified
directory.
The method will also remove any subdirectories of the specified directory.
If you want to empty a directory asynchronously, use the fsExtra.emptyDir()
method instead.
import fsExtra from 'fs-extra'; // ๐๏ธ if you use CommonJS require() // const fsExtra = require('fs-extra'); async function deleteAllInDir(dirPath) { try { await fsExtra.emptyDir(dirPath); } catch (err) { console.log(err); } } deleteAllInDir('./my-directory').then(() => { console.log( 'All files and subfolders in the directory have been deleted', ); });
The fsExtra.emptyDir()
method takes a path and deletes all files and
subfolders in the given path.
The method returns a Promise, so we used the async/await
syntax to wait for
the Promise to resolve.
You can learn more about the related topics by checking out the following tutorials: