Home > Software design >  Error: ENOENT: no such file or directory Nodejs
Error: ENOENT: no such file or directory Nodejs

Time:12-21

I'm trying to upload a file and store it in an uploads folder, but I get this error: no such file or directory I get the message success in console but I get this error anyway.

POST /auth/register 500 21.023 ms - 260
Error: ENOENT: no such file or directory, open E:\IMPORTANT\INFO-DEV\DEV\ANGULAR NODEJS\API AUTH\uploads\1671534381494.jpeg

Here is my configuration code for upload.

const path = require("path");
const multer = require("multer");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    const extension = path.extname(file.originalname);
    cb(null, Date.now()   extension);
  },
});
const upload = multer({
  storage: storage,
  fileFilter: function (req, file, callback) {
    if (
      file.mimetype == "image/png" ||
      file.mimetype == "image/jpg" ||
      file.mimetype == "image/jpeg"
    ) {
      callback(null, true);
      console.log("Image téléchargé avec succès"); // success message
    } else {
      callback(null, false);
      console.log("Seulement du fichier de type png, jpg ou jpeg"); // error message
    }
  },
  limits: {
    fileSize: 1024 * 1024 * 2,
  },
});

module.exports = upload;

CodePudding user response:

The issue is that your uploads folder doesn't exist or you set the path incorrectly.

I don't know where exactly you created uploads folder (and if you created it at all).

So in the destination param you should pass either:

path.join(__dirname, '/uploads') - in case that folder is in the same location where current js file is located.

Or path.join(process.cwd(), '/uploads') - in case if uploads folder is in the root of the project (where you run npm start etc.)

So, in short words you need to make sure folder exists and then make sure the path is correct.

P.S. Using ../../ syntax should also work, you can try ../uploads or ../../uploads if, for example, that folder is on higher levels of your folders structure.

CodePudding user response:

Change this line

cb(null, './uploads/');

this line cb(null, "uploads/");

or try cb(__dirname, "uploads/");

  • Related