使用节点文件系统和 MongoDB 从后端删除图像文件

remove image file from backend with node File System and MongoDB

我需要从后台删除一个图像文件,文件夹是:/uploads。当我调用 deleteProduct 函数时,它会从数据库中删除产品,但产品图像仍在文件夹中。

deleteProduct: (req, res) => {
        let productId = req.params.id;
        Product.findById(productId, (err, res) =>{
            var imageResponse = res.image; 
            console.log(imageResponse); 
        });
        //console.log(imageResponse);
        //fs.unlink('./uploads' + imageResponse );

当我尝试在 findById 之外访问 imageResponse 时,控制台打印:“imageResponse”未定义。然后我需要用 fs 删除那个文件。我不确定我是否写了正确的取消链接功能。提前致谢。

对于fs.unlink

您确定:

  1. 包括fs = require('fs')?
  2. 用过__dirname?
  3. 包括文件扩展名(.png、.jpg、.jpeg)?
const fs = require('fs');

fs.unlink(__dirname + '/uploads' + imageResponse + ".png", (err) => {
  if (err) throw err;
  console.log('successfully deleted file');
});

图像响应未定义

您没有提供有关 Product 构造函数的信息,但我假设 Product.findById 是异步的。您可能需要使用异步函数

const fs = require('fs');

async function deleteProduct (req, res) => {
        let productId = req.params.id;
        Product.findById(productId, (err, res) =>{
            var imageResponse = res.image; 
            console.log(imageResponse);
            fs.unlink(__dirname + '/uploads' + imageResponse + ".png", (err) => {
              if (err) throw err;
              console.log('successfully deleted file');
            });
        });
}

延伸阅读: 节点文件 API:https://nodejs.org/api/fs.html 异步函数:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

终于它似乎可以工作了,文件成功地从文件夹中消失了,我仍然开放寻求建议,谢谢。

deleteProduct: (req, res) => {
        let productId = req.params.id;
        Product.findById(productId, (err, res) =>{
            if(err) return res.status(500).send({message: 'Error'});
            fs.unlink('./uploads/' + res.image, (err) => {
                if(err) return res.status(500).send({message: 'Error'});
            })
});