0

我正在使用 fs-extra 库在我的节点 js 应用程序中根据发布请求删除一些图像文件。每次我打电话 /deleteproduct route 一切正常。我的产品已从数据库中删除,即使文件未删除,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 });  
}

});

编辑:图像文件位于公共目录的图像文件夹内。

目录图像

如果您需要更多信息,请发表评论

目录图像:

目录图像

cpanel.js正在删除文件

4

2 回答 2

1

这里可能有两个问题。首先,您没有使用正确的路径来正确引用您的文件。其次,您同时使用等待和回调。你可以做这样的事情。


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 块来捕获错误。

于 2021-06-15T14:40:53.117 回答
0

而不是这个:

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返回一个承诺,所以这应该工作。添加atry/catch来检查错误也可以实现

于 2021-06-15T14:32:40.087 回答