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


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:

        .then(post => {
            if (!post) {
                const error = new Error('Could not find post');
                error.statusCode = 404;
                throw error

            if (imageUrl == !post.imageUrl) {

            post.title = title;
            post.imageUrl = imageUrl;
            post.content = content;
            return post.save();



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

Answered By – Positivity

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published