【发布时间】:2022-02-15 21:17:21
【问题描述】:
当我在 NodeJS 中更新产品时,我想从 images 文件夹中删除旧图像,产品正在更新,但旧图像没有从文件夹中删除。
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'))
功能
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})
}
}
【问题讨论】:
-
我之前也遇到过这个问题,请尝试杀死您的应用并重新启动它。
-
fs.unlinkSync(oldImageUrl)不返回承诺