【发布时间】:2020-11-24 01:01:37
【问题描述】:
我需要从我的后端删除一个图像文件,该文件夹是:/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 删除那个文件。我不确定我是否写了正确的取消链接功能。提前致谢。
【问题讨论】:
-
res.image 应该是一个 url 。取 url ,转换为 fs 中的路径。从 fs 路径获取 'file' 的实例,当你有文件的引用时,在其上调用 delete
-
当我记录 imageResponse 时,我得到了产品图像的名称,然后我需要将该名称传递给文件系统取消链接功能,但我不知道如何,我无法在外部访问 imageResponse findById 函数
标签: javascript node.js mongodb fs