How to get rid of Error removing file: [Error: EPERM: operation not permitted, unlink] error from node fs

44 views Asked by At

This is the code

const express = require("express");
const multer = require("multer");
const path = require("path");
const sharp = require("sharp");
const fs = require("fs");
const cron = require('node-cron')
const app = express();

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./profiles");
  },
  filename: function (req, file, cb) {
    cb(
      null,
      file.fieldname + "-" + Date.now() + path.extname(file.originalname)
    );
  },
});

const upload = multer({ storage: storage });

app.use(express.urlencoded({ extended: false }));

app.post("/file-upload", upload.single("profile"), async (req, res) => {
  try {
    // Read uploaded image using sharp
    const inputFile = req.file.path;
    const outputFile = "cprofiles/" + req.file.filename;

    // Resize and crop the image to a certain width (e.g., 300px)
    await sharp(inputFile)
      .resize({ width: 300, height: 300, fit: "cover" })
      .toFile(outputFile);

    fs.unlinkSync(inputFile);
    
    res.send("Image uploaded and cropped successfully");
  } catch (err) {
    console.error(err);
    res.status(500).send("Error uploading and cropping image");
  }
});

const folderPath = "./profiles";

cron.schedule("*/1 * * * *", () => {
  fs.readdir(folderPath, (err, files) => {
    if (err) {
      console.error("Error reading folder:", err);
      return;
    }

    // Iterate over each file and remove it
    files.forEach(file => {
      const filePath = path.join(folderPath, file);
      fs.unlink(filePath, err => {
        if (err) {
          console.error("Error removing file:", err);
          return;
        }
        console.log(`File ${filePath} removed successfully`);
      });
    });
  });
});

app.listen(4000, () => {
  console.log("@ 4000");
});

This is the error I'm getting dont know what to do really worried searched all over the internet Please help

Error removing file: [Error: EPERM: operation not permitted, unlink 'C:\Users\NS\Desktop\multer\profiles\profile-1708017817484.jpg'] { errno: -4048, code: 'EPERM', syscall: 'unlink', path: 'C:\Users\NS\Desktop\multer\profiles\profile-1708017817484.jpg' }

I appreciate your time. Thank you

I tried re-installing node, npm, node_modules I'm getting this error even in linux and windows Also tried running the node in admin terminal still getting the error Permission also changed to read and write. Node Fs is giving the error. Please let me know is there any other modules. Also getting same erro using yarn

0

There are 0 answers