I have a delete route which deletes an image file. Following is the code:
router.delete('/:id', (req, res) => {
let pathForThumb = '';
let pathForImage = '';
Image.findOne({ _id: req.params.id })
.then(getImage => {
pathForThumb = getImage.thumbPath;
pathForImage = getImage.imagePath;
getImage.remove();
})
.then(removeThumb => {
fs.unlink(pathForThumb, (err) => {
if (err) {
req.flash('error_msg', 'There was an error deleting the thumbnail');
res.redirect('/user/userdashboard');
}
});
})
.then(removeMainImage => {
fs.unlink(pathForImage, (err) => {
if (err) {
console.log(err);
req.flash('error_msg', 'There was an error deleting the main image');
res.redirect('/user/userdashboard');
} else {
req.flash('success_msg', 'Image removed');
res.redirect('/user/userdashboard');
}
});
})
.catch(err => {
console.log(err);
});
});
as you can see when I upload a file I store it's path and also generate a thumbnail in the /uploads/thumbs/ folder and store the path of the thumb nail as well. In the above code I first get the image using findOne, store the paths of both images in variables and then call fs.unlink in a promise. What is happening is that my thumbnail gets deleted but I am getting the following error in the removeMainImage then condition:
{ Error: EBUSY: resource busy or locked, unlink 'C:\Users\Amin Baig\Desktop\Teaching\galleryprj\public\uploads\XC6kPqWf9_dphaBmUG__I7SN7PAEl_1531823330941_CEI21.jpg'
errno: -4082,
code: 'EBUSY',
syscall: 'unlink',
path: 'C:\\Users\\Amin Baig\\Desktop\\Teaching\\galleryprj\\public\\uploads\\XC6kPqWf9_dphaBmUG__I7SN7PAEl_1531823330941_CEI21.jpg' }
I am using windows 10 for my dev environment os. Have been trying to find a solution for this, please help.