Reputation: 159
I want to delete the old image from images folder when I update the product in NodeJS, product is updating, but old image is not deleting from the folder.
index.js
app.use(bodyParser.json({extended:true}))
app.use(bodyParser.urlencoded({extended:true}))
app.use(cors())
app.use('/', route)
app.use('/images', express.static('images'))
function
export const updateProduct = async (req, res)=>
{
try{
let image
const oldProduct = await Product.findOne({_id:req.params.id})
const {name,price,quantity,category} = req.body
if(req.file)
{
image = req.file.filename
const oldImageUrl= `/images/${oldProduct.image}`
// this is url of the old image http://localhost:2001/images/1629969633380_r.png
await fs.unlinkSync(oldImageUrl)
}else{
image = oldProduct.image
}
const productToUpdate = new Product({name,category,quantity,price,image})
await Product.updateOne({_id:req.params.id},productToUpdate)
res.status(200).json('product Updated')
}catch(error)
{
res.status(404).json({message:error.message})
}
}
Upvotes: 1
Views: 3180
Reputation: 138
router.post('/update/:id', upload.single("file"), async (req, res) => {
let data = {
name: req.body.name,
price: req.body.price,
quantity: req.body.quantity,
discount: req.body.discount,
discription: req.body.discription,
file: req.file.filename
}
const oldProduct = await products.findOne({ _id: req.params.id });
const result = await products.findByIdAndUpdate(req.params.id, data,);
fs.unlink('./public/image/' + oldProduct.file, function (err) {
if (err && err.code == 'ENOENT') {
// file doens't exist
console.info("File doesn't exist, won't remove it.");
} else if (err) {
// other errors, e.g. maybe we don't have enough permission
console.error("Error occurred while trying to remove file");
} else {
console.info(`removed`);
}
});
res.redirect('/listProducts');
})
Upvotes: 0
Reputation: 20467
Based on this bit of code:
app.use('/images', express.static('images'))
You should try to delete the image relative to the app folder.
const oldImageUrl= `images/${oldProduct.image}`
Or even better yet, use the path
module.
const { join } = require('path');
...
const oldImageUrl = join(__dirname, 'images', oldProduct.image);
Upvotes: 1