user16364975
user16364975

Reputation:

How to delete file in nodejs and reactjs?

I am uploading images into my PC storage with reactjs and nodejs, so in my project, I have posts, and each post can have only one image, the images are storing in the pc with the post id.

for example

postId = 120 

image id = 120

#For my post, I have a SQL database, but I am not "sending any image" to the database. and now I want to delete the image that belongs to a specific post when I delete the post.

Here is some code for deleting the post.

    // Delete  post
router.delete("/:postId", validateToken, async (req, res) => {
  const postId = req.params.postId;
  await Posts.destroy({
    where: {
      id: postId,
    },
  });
  res.json("post deleted successfully!");
});

This is how I implement the creating post on the server-side.

router.post("/", validateToken, async (req, res) => {
  const files = req.files;
  let file = null;
  const userId = req.user.id;

  const post = req.body;

  post.fullName = req.user.fullName;
  post.UserId = userId;
  const createdPost = await Posts.create(post);
  const postId = createdPost.id;

  if (files && Object.keys(files).length > 0) {
    file = files.file;
    const dir = `/imageUpload/${postId}`;
    fs.access(dir, (error) => {
      if (error) {
        fs.mkdir(dir, (error2) => {
          if (error2) {
            res.status(500).send("Failed to create the directory!");
          } else {
            writeFileToFolder(file, res, postId);
          }
        });
        console.log("Directory does not exist.");
      } else {
        writeFileToFolder(file, res, postId);
        console.log("Directory exists.");
      }
    });
  } else {
    res.json(post);
  }
});

any idea?

Upvotes: 0

Views: 2600

Answers (1)

krunal
krunal

Reputation: 80

You can try fs.unlink()

router.delete("/:postId", validateToken, async (req, res) => {
    const postId = req.params.postId;
    const imagePath = `/imageUpload/${postId}`;
    fs.unlinkSync(imagePath);
    await Posts.destroy({
      where: {
        id: postId,
      },
    });
    res.json("post deleted successfully!");
});

Upvotes: 1

Related Questions