问题描述
我正在使用 fs-extra 库在我的节点 js 应用程序中根据发布请求删除一些图像文件。每次我调用 /deleteproduct 路由时一切正常。我的产品已从数据库中删除,即使文件未删除,fs-extra 回调也不会引发任何错误!我不知道是什么原因。我想也许我在 async/await 函数上做错了什么。
这是我的代码:
router.post('/deleteproduct',async (req,res) => {
try {
const id = req.body.id;
const deleteProduct = await prisma.product.findUnique({
where: { id: id }
});
const images = JSON.parse(deleteProduct.image);
for(let i = 0; i < images.length; i++) {
await fsExtra.remove(path.join(__dirname,`public/images/${images[i]}`),(err) => {
if (err) console.log(err);
});
console.log(images[i]);
}
await prisma.product.delete({
where: { id: id }
});
res.status(200).json({ msg: "Deleted product with id: " + id });
} catch (error) {
res.json({ msg: error });
}
});
如果您需要更多信息,请发表评论
目录图像:
解决方法
这里可能有两个问题。首先,您没有使用正确的路径来正确引用您的文件。其次,您同时使用 await 和回调。你可以做这样的事情。
try {
const images = JSON.parse(deleteProduct.image);
const imageProm = [];
for(let i = 0; i < images.length; i++) {
imageProm.push(fsExtra.remove(path.join(__dirname,`public/images/${images[i]}`)
}
const result = await Promise.all(imageProm);
await prisma.product.delete({
where: { id: id }
});
}
catch (e) {console.log(e)}
如果上述解决方案不起作用,为什么您不能使用 fs.unlink
为此类情况提供的本机方法。尝试使用它。
注意:每当您使用 async/await 时,请使用 try/catch 块来捕获错误。
,取而代之的是:
await fsExtra.remove(path.join(__dirname,`public/images/${images[i]}`),(err) => {
if (err) console.log(err);
});
你能不能直接试试这个:
await fsExtra.remove(path.join(__dirname,`public/images/${images[i]}`));
fs-extra
返回一个承诺,所以这应该有效。添加一个try/catch
来检查错误也可以实现