How to remove image file/ literally a file from a node js-express server

577 views Asked by At

I'm a beginner in web development field and as my first project i'm trying to create a basic E-commerce application, I'm succeeded most of my way but now stuck in removing the image file of the product: I'm using express-generator to create the server, i didn't change any default variable and only added mongodb api.

router.get('/deleteProduct/:id', (req, res) => {
    let productId = req.params.id;
    productsHelper.deleteProduct(productId).then((response) => {
        res.redirect('/admin/');
    });
}
    
module.exports.deleteProduct: (productId) => {
    return new Promise((resolve, reject) => {
                
        db.get().collection(collections.PRODUCT_COLLECTIONS).removeOne({_id:objectId(productId)}).
        then((response) => {
            resolve(response);
        });
    });
};

I also tried fs

**this my first time ever on stackoverflow ...

1

There are 1 answers

1
Rajika Imal On BEST ANSWER

You can remove the file after the database call is successful,

const fs = require("fs");

module.exports.deleteProduct = (productId) => {
  return new Promise((resolve, reject) => {
    db.get()
      .collection(collections.PRODUCT_COLLECTIONS)
      .removeOne({ _id: objectId(productId) })
      .then((response) => {
        const path = "./file.png";
        fs.unlink(path, (err) => {
          if (err) {
            console.error(err);
            reject(err);
          }

          console.log("File removed");
          resolve(response);
        });
      });
  });
};