How to Delete all Files in a Directory using Node.js

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
4 min

banner

# Table of Contents

  1. How to Delete all Files in a Directory using Node.js
  2. How to Delete all Files in a Directory Synchronously using Node.js
  3. How to Delete all Files in a Directory using fs-extra

# How to Delete all Files in a Directory using Node.js

To delete all files in a directory using Node.js:

  1. Use the fs.readdir() method to get the names of the files in the directory.
  2. Use the fs.unlink() method to delete each file.
  3. Use the Promise.all() method to await the Promises returned from the fs.unlink() method.
index.js
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'); });

delete all files in a directory using node js

The code for this article is available on GitHub

The code sample above uses the ES6 modules import/export syntax.

If you use the CommonJS require() syntax, use the following import statements instead.

index.js
const fs = require('fs/promises'); const path = require('path');

The example assumes that your project has the following folder structure.

shell
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.

index.js
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 code for this article is available on GitHub

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.

index.js
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.

index.js
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.

index.js
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.

index.js
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 for this article is available on GitHub

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.

# How to Delete all Files in a Directory Synchronously using Node.js

You can also delete all files in a directory synchronously.

index.js
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');

delete all files in directory synchronously using node js

The code for this article is available on GitHub

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.

index.js
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.

index.js
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');
The code for this article is available on GitHub

# How to Delete all Files in a Directory using fs-extra

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.

shell
npm init -y

Use the following command to install the fs-extra package.

shell
# with NPM npm install fs-extra # or with YARN yarn add fs-extra

npm install fs extra package

Import and use the package to delete all files in the given directory.

index.js
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); }

delete all files in directory using fs extra

The code for this article is available on GitHub

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.

index.js
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 code for this article is available on GitHub

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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev