我尝试更新帖子,但是fs.unlink()不会删除本地文件夹中的旧文件。在我的集合中,图像路径似乎随着旧路径的替换而更新。我不知道为什么老照片还保留在我的本地文件夹中。更新控制器可以工作,因为其他内容都会更新。
我使用这个函数来删除
const clearImage = filePath => {
filePath = path.join(__dirname, "..", filePath);
fs.unlink = (filePath, err => console.log(err)); 我在这里叫clearImage:
Post.findById(postId)
.then(post => {
if (!post) {
const error = new Error('Could not find post');
error.statusCode = 404;
throw error
}
if (imageUrl == !post.imageUrl) {
clearImage(post.imageUrl);
}
post.title = title;
post.imageUrl = imageUrl;
post.content = content;
return post.save();
})发布于 2022-08-06 09:11:25
您应该比较这样的字符串:
if (imageUrl !== post.imageUrl)而不是这样:
if (imageUrl == !post.imageUrl)然后像这样调用unlink函数:
fs.unlink(filePath, err => console.log(err)); 而不是这样:
fs.unlink = (filePath, err => console.log(err)); https://stackoverflow.com/questions/73258504
复制相似问题