1

I have been trying to delete a specific file in a nested directory.

import Express from 'express';
import { baseURL } from '..';
import fs from 'fs';
import path from 'path';
import { GuestFile } from '../models/guest-file';

export const GuestDelete = async (request: Express.Request, response: Express.Response) => {
const { identifier } = request.params;

const find_file = await GuestFile.findOne({ identifier });

if (!find_file) {
return response.status(404).json({ error: 'File not found', success: false });
}

const local_file_path = find_file.file_url?.split(`${baseURL}`).pop();
const file_name = local_file_path?.split('/')?.splice(-1)[0];

// Here is where the problem is *********
fs.readdirSync(path.join(__dirname + `/uploads/${find_file.type}s/`)).find((file) =>      console.log(file));

console.log('file_name', file_name);

response.status(204).json({ success: true, identifier });
};

// deleteFileAfterDelay();

`

So I'm trying first to delete the file from the database, then delete it locally from uploads, and as you can see in the image, the uploads folder has a subdirectory. I wanted to be able to map through all the files in the subdirectory, and if the file_name matches with the file then I fs.unlinkSyn, but keep getting errors. Then the path ends up being this C:\\Users\\essel_r\\Desktop\\everfile\\backend_api\\\src\\controllers\\uploads\\images\\

This is what the directory looks like: Image of the directory structure

I tried using the fs.unlinkSyn() and it didn't work: fs.readdirSync('/uploads/${find_file.type}/').find((file) => file === file_name && fs.unlinkSync(file_name)); I also tried using the fs.access() to check if the file exists, but that too didn't work.

Ken White
  • 123,280
  • 14
  • 225
  • 444

2 Answers2

0

I try to run your code. I change 'import fs from 'fs' => 'const fs = require('fs')' and 'import path from 'path' => 'const path = require('path')'

And in my case, it works well.

//import fs from 'fs';
const fs = require('fs')
// import path from 'path';
const path = require('path')

fs.readdirSync(path.join(__dirname + `/uploads/subDir`)).find((file) =>
  console.log(file)
);
Alex Choi
  • 144
  • 7
0

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

Whole Code: index.ts

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

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


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}`);
 })
 }

  });
 });
});

For more Info