0
46
11:30 AM

How to delete a specific file inside a nested folder

Feb 15th 232 Minutes

How to delete a specific file inside a nested folder

After trying a lot last night and this morning, this is how i did it, so I'll be explaining it well.

import fs from 'fs'
import path from 'path'

const directory = path.join(__dirname, '..', 'src', 'uploads', 'images')
const file_to_delete = '1676410030129-screen.webp'

the src, uploads, and images are nested directories in my folder structure.

src
 -controllers
 -models
 _uploads
    -images
      -1676410030129-screen.webp
    -audio
    -videos

Code:

fs.readdir(f, (error, files) => {
if (error) throw new Error('Could not read directory');

files.forEach((file) => {
const file_path = path.join(f, file);
console.log(file_path);

fs.stat(file_path, (error, stat) => {
  if (error) throw new Error('File do not exist');

  if(stat.isDirectory()){
    console.log('The file is actually a directory')
  }else if (file === file_to_delete ) {
    fs.unlink(file_path, (error)=> {
      if (error) throw new Error('Could not delete file');
        console.log(`Deleted ${file_path}`);
    })
  }

    });
   });
  });

Explanation: we first read the directory of the files we want, then if we encounter an error, when we throw the error, or we get the files, which is an array. we grab each file and then join the directory to the file, so we get something like this `C:\Users\..\Desktop\..\..\src\uploads\images\1676410030129-screen.webp` Then we use `fs.stat` to check if the path to the file exists. So if the file doesn't exist we throw an error, or we also check if the path to the actual file is a directory `stat.isDirectory()` if true, we `console.log('The file is actually a directory)`, if it is false, then we move to the next line of the code, and check if the file is which `C:\User\..\1676410030129-screen.webp` is strictly equal to the `file_to_delete` then we delete the file, else we throw another error.

Then hoe about, we make it into a function:

const directory = path.join(__dirname, '..', 'src', 'uploads', 'images');

export const handleFileDeletion = (directory: string, file_to_delete: string) => {
  fs.readdir(directory, (error, files) => {
    if (error) {
      console.log(error);
      throw new Error('Could not read directory');
    }

    files.forEach((file) => {
      const file_path = path.join(directory, file);

      fs.stat(file_path, (error, stat) => {
        if (error) {
          console.log(error);
          throw new Error('Could not stat file');
        }

        if (stat.isDirectory()) {
          // Here instead of doing a consle.log(),
          // we recursively search for the file in subdirectories
          handleFileDeletion(file_path, file_to_delete);
        } else if (file === file_to_delete) {
          fs.unlink(file_path, (error) => {
            if (error) {
              console.log(error);
              throw new Error('Could not delete file');
            }

            console.log(`Deleted ${file_path}`);
          });
        }
      });
    });
  });
};

handleFileDeletion(directory, '1676410030129-screen.webp')

Reach out

Resource

0 comment
Be the first to leave a comment