nodejs-rest-api-delete-image

Delete Uploaded Image Using Nodejs API

This Rest API tutorial help to delete images from folder using nodejs. This is the second part of the tutorial Create Nodejs API to Upload file Using Multer.

I will create HTTP DELETE Rest API to delete the uploaded images from the server.

We will now extend the code from the previous tutorial by adding a delete image API using the nodejs express framework. I’m passing the image name as a parameter; you can pass an id or other parameters based on your needs. The fs module in nodejs allows you to work with your computer’s file system.

Rest API to Delete Image

I’m assuming you’ve already set up my previous tutorial, If you don’t know how to integrate code, don’t worry. This code can also be integrated into an existing Nodejs app. I’ll walk you through the steps of creating a delete image API one by one.

Import Node.js file system module

We will import fs module into the main nodejs entry file, I am adding the below line into app.js file.

,fs = require('fs')

Nodejs API to Delete Image

Let’s make a new rest endpoint to delete an image. We’ll add the code below to this file.

const DIR = 'uploads';
app.delete('/api/v1/delete/:imagename',function (req, res) {
  message : "Error! in image upload.";
    if (!req.params.imagename) {
        console.log("No file received");
        message = "Error! in image delete.";
        return res.status(500).json('error in delete');
    
      } else {
        console.log('file received');
        console.log(req.params.imagename);
        try {
            fs.unlinkSync(DIR+'/'+req.params.imagename+'.png');
            console.log('successfully deleted /tmp/hello');
            return res.status(200).send('Successfully! Image has been Deleted');
          } catch (err) {
            // handle the error
            return res.status(400).send(err);
          }
        
      }

});

Here, The variable imagename will contain the image name that you want to delete. The unlinkSync method of the fs module can be used to remove an image from a folder path. The upload directory path will be stored in the DIR constant.

If everything fine, You will get a success message ‘Successfully! Image has been Deleted’ otherwise get ‘error in delete’ message.