title: NodeJS & Multer: stop uploading file if error occurs
body: <p>hello i creating file upload with Node &amp; Multer, it works but problem is that if error occur (like user did not fill other fields) it still uploads file which i don't want</p>
  
  <p>i literally don't know what to do because i am doing it first time so wish if anyone got experience with this. here is my code</p>
  
  <pre><code>const storage = multer.diskStorage({
  
    destination: (req, file, callback) =&gt; {
      const userPath = path.join(imgStoragePath, req.userId);
      fs.mkdir(
        userPath,
        () =&gt; callback(null, userPath)
      )
    },
  
    filename: (req, file, callback) =&gt; {
      const filenameParts = file.originalname.split('.');
      const ext = filenameParts.pop();
      const basename = filenameParts.join('.');
      const additionalPath = Date.now() + '' + uuid() + '' +             
  Math.floor(Math.random() * (2000 - 500)) + 500;
      callback(null, basename + '-' + additionalPath + '.' + ext);
    }
  
  })
  
  const upload = multer({
    storage,
    limits: '1mb'
  })
  
  
     router.post('/', upload.single('image'), async (req, res) =&gt; {
    //code
  })
  </code></pre>
  
  <p>if error occurs it should return error message and send it to server and stop code execution and don't do anything, it does it but also uploads file, i know this will happen because <code>upload</code> is middleware and middleware executes first and i want it to prevent it. Thanks!</p>