DEV Community

Cover image for Deleting multiple directories with Nodejs/Javascript
Ethan
Ethan

Posted on

3 2

Deleting multiple directories with Nodejs/Javascript

Hello! I had to delete all directories that were in a directory called "files", just thought I'd share the solution. ๐Ÿ˜ƒ

const { rmSync, promises: { readdir } } = require('fs');

(async () => {
  try {
    const fileNames = await readdir('./files');

    for (const fileName of fileNames) {
      console.log(`deleting file with name ${fileName}`);
      rmSync(`./files/${fileName}`, { recursive: true }); 
    }   
  } catch (error) {
    console.error('failed to delete directories', error);
  }
})();
Enter fullscreen mode Exit fullscreen mode

Short and sweet. ๐Ÿ˜Ž

What this basically does is read all the directories under the directory called "files" and puts them into an array of file names using the readdir function.

Then it loops through the names of the directories and deletes them using rmSync.

Also it's very important to handle errors with nodejs as an unexpected error may kill the application. ๐Ÿฅฒ

If you have a better, cleaner solution then please share. This is how I handled it. ๐Ÿ™‚


Like me work? I post about a variety of topics, if you would like to see more please like and follow me.
Also I love coffee.

โ€œBuy Me A Coffeeโ€

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)