As a final touch to the file handling in your back end, make sure that whenever a Thing is deleted from the database, the corresponding image file also gets deleted.
In your stuff controller, import the Node fs package:
const fs = require('fs');Now you can modify your deleteThing() function:
exports.deleteThing = (req, res, next) => {
Thing.findOne({_id: req.params.id}).then(
(thing) => {
const filename = thing.imageUrl.split('/images/')[1];
fs.unlink('images/' + filename, () => {
Thing.deleteOne({_id: req.params.id}).then(
() => {
res.status(200).json({
message: 'Deleted!'
});
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
});
}
);
};In this function:
Use the ID you receive as a parameter to access the corresponding Thing in the database.
Use the fact that you know there is an /images/ segment in your image URL to separate the file name.
Then use the fs package's unlink function to delete that file, passing it the file to be deleted and the callback to be executed once that file has been deleted.
In the callback, implement the original logic, deleting the Thing from the database.
Your API can now successfully handle all CRUD operations containing files: when a user creates a new Thing , updates an existing Thing , or deletes a Thing !
The built-in fs package exposes methods for interacting with the server's file system.
fs' unlink() method lets you delete a file from the file system.
You're nearly finished. Well done!
Let's have a look at what you've learned: