I am very new to back-end development with node and mongodb so i am unsure if this is the right aproach and i am also developing all this on Windows.
I am trying to delete a document and the files that document uses in a mongodb collection of notes (they might as well be posts), each note has a note image wich is uploaded through a form with multer, this form submits the new note and the uploaded image path to a new mongodb document in a "notes" collection.
I want to be able to delete the note (mongodb document) as well as the images that the document holds (document holds their paths), there is an image which is uploaded in the form with multer and there is a thumbnail of this image generated with sharp.
Both images are saved to public/img/uploads/notes/ and they just differ by the thumbnail sufix: "_thumb".
So far i can remove the note (document in mongodb) and the thumbnail but i get an error while trying to remove the note image.
This is what im doing:
router.post('/admin/notes/:id/delete', (req, res) => {
Note.findOne({_id: req.params.id}).then(note => {
let thumbPath = `./public/${note.thumbPath}`;
let imagePath = `./public/${note.imagePath}`;
note.remove().then(err => {
if (err) {
console.log(err);
}
fs.unlink(thumbPath, err => {
if (err) {
console.log('failed to delete note thumbnail:' + err);
} else {
console.log('successfully deleted note thumbnail');
}
});
fs.unlink(imagePath, err => {
if (err) {
console.log('failed to delete note image:' + err);
} else {
console.log('successfully deleted note image');
}
});
res.redirect('/admin/notes');
});
});
});
When i create a new note and then try to delete the note, i always get this for the image
Error: EBUSY: resource busy or locked, unlink path/to/the/image
The image can be removed after node process ends, even when i restart node, the image is no longer busy, regardless of whether I deleted the note that was using that image or not, so it seems to me that the problem comes from the moment i upload the image rather than the moment where i use it.
So the question in place: How can i make node release the busy file so i can delete it?
via Richard CDSP
No comments:
Post a Comment