I have a function that loops over an array that contains paths to files, then I delete each of them. The files are uploaded with Multer in a folder "assets/temp/" Here is my delete method using fs :
exports.unlinkFiles = (filesPathsArr) => {
try {
filesPathsArr.forEach((filePath) => {
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath)
console.log('File deleted : ', filePath)
}
})
} catch (error) {
throw error
}
}
My input for example :
['assets\temp\pexelsphoto19886811645117462309.jpg', 'assets\temp\relaxtriptest1645118333937.mp3']
My output :
File Deleted : assets\temp\pexelsphoto19886811645117462309.jpg
File Deleted : assets\temp\relaxtriptest1645118333937.mp3
But in my folder temp :
+ And if I try to open the file, it say 'Enable to read..'
+ When I restart the server, the file just disapear
Is this just a local problem with my machine, maybe the problem will go away in production? Or maybe it's just a small detail that I shouldn't worry about? Or is it something else ?
I solved the problem !
After uploading the file with Multer, I upload it to AWS S3.
But the problem is that if there is an error with the AWS code, then I throw an exception and then delete the uploaded files from the temporary directory. But by doing this, I didn't let the AWS function finish and so the readstream was still open.
The solution then was to myReadStreamCreated.destroy() at the end of the function and also in the catch of the try catch bloc, if an exception is thrown, to allow fs.unlink to be able to delete the file correctly.
Thank's to ruby-newbie