Home > Blockchain >  fs.unlink not deleting file in local folder after updating item
fs.unlink not deleting file in local folder after updating item

Time:08-07

I try to update posts but fs.unlink() doesen't remove the older files in my local folder. In my collection, the image path seem to be updated as the old path is replaced. I don't know why the old images are still retained in my local folder. The update controller works since everything else gets updated.

I use this function for the deletion

        const clearImage = filePath => {
        filePath = path.join(__dirname, "..", filePath);
        fs.unlink = (filePath, err => console.log(err)); 

I call clearImage here:

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();

        })

CodePudding user response:

You should compare strings like this:

if (imageUrl !== post.imageUrl)

instead of this:

if (imageUrl == !post.imageUrl)

And call the unlink function like this:

fs.unlink(filePath, err => console.log(err)); 

Instead of this:

fs.unlink = (filePath, err => console.log(err)); 
  • Related