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.