Reputation: 139
I'm trying to delete only certain files from a folder which are uploaded using multer.
First, I create a hash, and add a date to order the array, once I have the array with the files, I try to delete from the third element in advance, but it doesn't work. I don't know if it's because unlink doesn't work with arrays.
This is my code
upload(request, response, function (err: any) {
fs.readdir('public/avatars/', (err: any, files: any) => {
if (err) throw err;
for (const file of files) {
let arrayofAvatars = [];
arrayofAvatars.push(files);
arrayofAvatars.sort();
if(arrayofAvatars.length>5) {
for (let i=2; i<=arrayofAvatars.length; i++) {
fs.unlink(path.join('public/avatars/', arrayofAvatars[i]), (err: any) => {
if (err) throw err;
});
}
}
}
});
if ((err) && (err.code === 'LIMIT_FILE_SIZE')) {
response.status(400).json({ response: { errorCode: 'ERRUAA03'} });
}
else if (err) {
response.status(400).json({ response: { errorCode: 'ERRUAA01' } });
} else {
response.status(200).json({ response: { imageName } });
}
});
Upvotes: 0
Views: 40
Reputation: 1161
Just one thing to point out: You are adding all the files into the arrayOfAvatars in each execution of the loop. Is that necessary?
I'd try something like this, instead:
upload(request, response, function (err: any) {
fs.readdir('public/avatars/', (readdirErr: any, files: any) => {
if (readdirErr) throw readdirErr;
// files is an array of strings containing the file names - you can sort it directly
files.sort();
// Now loop through and keep deleting
for(let idx = 2; idx < files.length; idx++) {
fs.unlink(path.join('public/avatars/', files[idx]), (unlinkErr) => {
throw unlinkErr;
});
}
});
if ((err) && (err.code === 'LIMIT_FILE_SIZE')) {
response.status(400).json({ response: { errorCode: 'ERRUAA03'} });
} else if (err) {
response.status(400).json({ response: { errorCode: 'ERRUAA01' } });
} else {
response.status(200).json({ response: { imageName } });
}
});
CAVEAT #1: I assume you know that ALL the "unlink" operations will run concurrently in this case, since the "for" loop will not wait for an unlink operation to complete before it executes the next iteration.
CAVETA #2: I hope that somewhere in your code, you have a handler for an uncaught exception. If the last file unlink operation throws an error, it is most likely that this closure is done and dusted, and that the thrown error will go "uncaught"
GENERAL HINT #1: I'd look into fs/promises and use the async/await syntax to run the deletions, etc. in series.
GENERAL HINT #2: If deleting files in serial order is too slow for you, I'd at least use a promise collection with parallel execution set to 5 or something similar. Look at the documentation of the bluebird library for examples, etc.
Upvotes: 1